2

I'm a beginner in google maps and JavaScript.

I'm creating a random markers on google map using Maps API V3, I want to create a list on the side that contain all Markers Id so when i click on Marker ID it will zoom in, on the map to show the marker. specifically i want to know how to create that link in javascript

thank you

jprbest
  • 717
  • 6
  • 15
  • 32

2 Answers2

2

This answer is from beginner to beginner ;) I like benastan's answer for succinctness and the application of closure, still I'd like to show a more "basic" approach by writing functions.

I don't feel qualified to talk about closures and function scopes, but I can say from experience these closure "wrappers" prevent unexpected behavior from functions called within loops or within other functions. One such bug could be a loop iterator value ending up all the same value (last iteration) or undefined. (my own example)

Link to full code: http://jsfiddle.net/WaWBw/

Click on the map to place markers, and clicking on markers or links on the side zooms in.

  function addMarker(pos) {
    var marker = new google.maps.Marker({
      map: map,
      position: pos
    });
    markers.push(marker);
    count = markers.length - 1;
    addMarkerListener(marker, count, 6);
    makeDiv(count, 4, "Marker #");
    count++;
  }

  function addMarkerListener(marker, index, zoomLevel) {
    google.maps.event.addListener(marker, 'click', function(event) {
      zoomIn(index, zoomLevel);
    });
  }

  function makeDiv(index, zoomLevel, content) {
    document.getElementById("sidebar").innerHTML += '<div onclick="zoomIn(' + index + ',' + zoomLevel + ')">' + content + ' ' + index + '</div>';
  }

  function zoomIn(index, zoomLevel) {
    map.setCenter(markers[index].getPosition());
    map.setZoom(zoomLevel);
  }
Community
  • 1
  • 1
Heitor Chang
  • 6,038
  • 2
  • 45
  • 65
1

Say you have a set of lat/lng coordinates:

var coords = [[32, -70], [50, -10], [0, 20]];

Loop through the coordinates, plotting the marker on your map and generating the list items. Bind the click handler at the same time:

var tpl = '<a href="javascript: void(0)">Click here to view a point</a>';
// Loop through coordinates.
for (var i in coords) {
    // Create a closure.
    (function() {
        var pt = coords[i],
            latlng = new google.maps.LatLng(pt[0], pt[1]),
            marker = new google.maps.Marker({
                position: latlng,
                map: map // variable containing your google map.
            }),
            elm = document.createElement('li');
        elm.innerHTML = tpl;
        // When you click the list item, set map center to latlng of marker.
        elm.onclick = function() {
            map.setCenter(latlng);
        };
        document.body.appendChild(elm);
    })();
}
benastan
  • 2,268
  • 15
  • 14