2
\$\begingroup\$

I have the following block of code which adds pins including descriptions and links onto a Google map. How can I refactor it so that I can add pins easier and without so much redundant code?

var map;

function initializeMap() {
var myOptions = {
    zoom: 9,
    center: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    scrollwheel: false
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker1 = new google.maps.Marker({
    position: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    map: map,
    title: "Pin 1",
    url: "#tabs-pin1"
});
google.maps.event.addListener(marker1, 'click', function() {
    $("#tabs").tabs('select', marker1.url);
});
var marker2 = new google.maps.Marker({
    position: new google.maps.LatLng(41.9584457, -70.6672621),
    map: map,
    title: "Pin 2",
    url: "#tabs-pin2"
});
google.maps.event.addListener(marker2, 'click', function() {
    $("#tabs").tabs('select', marker2.url);

var marker9 = new google.maps.Marker({
    position: new google.maps.LatLng(42.445921, -71.2690294),
    map: map,
    title: "Pin 9",
    url: "#tabs-pin9"
});
google.maps.event.addListener(marker9, 'click', function() {
    $("#tabs").tabs('select', marker9.url);

}
google.maps.event.addDomListener(window, 'load', initializeMap);
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

The simplest solution is extract one function that will form the marker from the parameters and them call it as many times as markers count is:

var markers = [];    // probably you don't need this array
function CreateMarker(lat, lng, markerTitle, markerUrl)
{
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    title: markerTitle,
    url: markerUrl
});
google.maps.event.addListener(marker, 'click', function() {
    $("#tabs").tabs('select', marker.url)
});

markers.push(marker); // you can omit this step if you are not going to work with markers after
}

function initializeMap() {
var myOptions = {
    zoom: 9,
    center: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    scrollwheel: false
};

CreateMarker(42.2340464046899, -71.0956621170044, "Pin 1", "#tabs-pin1");
// repeat this call for every marker
}
\$\endgroup\$
2
  • \$\begingroup\$ I think you missed a ); after the second block. \$\endgroup\$
    – Joe
    Commented Feb 10, 2012 at 0:46
  • \$\begingroup\$ Oh, yeah. Sorry, updated the code. \$\endgroup\$
    – Kate
    Commented Feb 10, 2012 at 0:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.