Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

javascript - Get Latitude and Longitude on click event from Google map

I have implemented the Google map successfully. But one more thing has left to do. I need to retrieve the Longitude and Latitude data when the user clicks on the map (any co-ordinates). My entire code looks like this:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var map;
  function initialize() {
      var myLatlng = new google.maps.LatLng(<?=$decimalValueLon?>,<?=$decimalValueLat?>);
      var myOptions = {
      zoom: 17,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.SATELLITE
    };


    map = new google.maps.Map(document.getElementById('map_canvas'),
        myOptions);

    // marker STARTS    
    var marker = new google.maps.Marker({
    position: myLatlng, 
    title:"Click to view info!"
});  
    marker.setMap(map);
    // marker ENDS

    // info-window STARTS   
    var infowindow = new google.maps.InfoWindow({ content: "<div class='map_bg_logo'><span style='color:#1270a2;'><b><?=$row->bridge_name?></b> (<?=$row->bridge_no?>)</span><div style='border-top:1px dotted #ccc; height:1px;  margin:5px 0;'></div><span style='color:#555;font-size:11px;'><b>Length: </b><?=$row->bridge_length?> meters</span></div>" });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
    // info-window ENDS 
 }

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

Thanks in advance !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add a click-handler like you have a load handler:

google.maps.event.addListener(map, "click", function (e) {

    //lat and lng is available in e object
    var latLng = e.latLng;

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...