2014-09-10 100 views
0

我想通过点击谷歌地图添加标记。 我使用此链接Google map V3 user adding markers如何通过点击谷歌地图添加标记

但这个例子不能帮助我。 这是我的代码:

<script> 
     var locations = <?=$json?>; 
     function initialize() { 
      addMarker(42.862101,74.610684); // add markers on map 
     } 

     google.maps.event.addDomListener(window, 'load', initialize); 
</script> 

函数从mysql数据库中添加标记:

<script> 

    function addMarker(x,y){ 
     var myLatlng = new google.maps.LatLng(x,y); 
     var mapOptions = { 
      zoom: 8, 
      center: myLatlng, 
      minZoom: 3 
     } 
     var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
     var contentString = '<div id="content">'+ 
      '<div id="siteNotice">'+ 
      '</div>'+ 
      '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+ 
      '<div id="bodyContent">'+ 
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' + 
      'Heritage Site.</p>'+ 
      '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+ 
      'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+ 
      '(last visited June 22, 2009).</p>'+ 
      '</div>'+ 
      '</div>'; 
     var infowindow = new google.maps.InfoWindow({ 
      content: contentString 
     }); 
     var marker; 
     for (var i = 0; i < locations.length; i++) { 
      marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(locations[i]['coord_lat'], locations[i]['coord_lng']), 
       map: map 
      }); 
      //something details 
      google.maps.event.addListener(marker, 'click', (function(marker, i) { 
       return function() { 
        infowindow.setContent(locations[i]['nameid']); 
        infowindow.open(map, marker); 
       } 
      })(marker, i)); 
     } 
    } 
</script> 

回答

0
# Add marker where user clicks map 
var map = new google.maps.Map(document.getElementById("map"), { 
    zoom: 5, 
    center: new google.maps.LatLng(40.747688, -74.004142), 
    mapTypeId: google.maps.MapTypeId.ROADMAP  
}); 

google.maps.event.addListener(map, 'click', function(e) {   
    var marker = new google.maps.Marker({ 
     position: e["latLng"], 
     title: "Hello world!" 
    });  
    marker.setMap(map); 
});   

试试吧http://jsfiddle.net/4hf78ag7/

+0

非常感谢你。对不起,我不能给你,你的答案是好的,我没有权限。万分感谢。 – 2014-09-11 04:47:11