Google Maps API V3: How to jump to a specific marker from outside the map?

前端 未结 1 420
借酒劲吻你
借酒劲吻你 2021-02-03 10:52

I have a map with two markers on it.

The initial view of the map only shows one marker, and I want to provide a link next to the map that will move the map to the 2nd m

相关标签:
1条回答
  • 2021-02-03 11:41

    Use addDomListener to add a click event to the link that will move the map to that marker (you'll also need to add an id to the link tag so you can reference it in code):

    Edit: Set the event in a initialization function:

    <head>
      <script type="text/javascript"> 
        function initialize() {
          var myLatlng = new google.maps.LatLng(-34.397, 150.644);
          var myOptions = {
            zoom: 8,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          }
          var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
          var marker2 = new google.maps.Marker({ position: new google.maps.LatLng(51.5262405, -0.074549), map: map, title: 'my 2nd title'});
          google.maps.event.addDomListener(document.getElementById("linkID"), "click", function(ev) {
            map.setCenter(marker2.getPosition());
          }
        }
      </script> 
    </head> 
    <body style="margin:0px; padding:0px;" onload="initialize()"> 
      <a href="javascript:function() { return false; }" id="location2">Second place</a>
      <div id="map_canvas" style="width:100%; height:100%"></div> 
    </body>
    
    0 讨论(0)
提交回复
热议问题