Google Maps HTML5 click to get lat, long

后端 未结 3 931
一生所求
一生所求 2020-12-25 11:23

I\'m trying to build a mobile HTML5 webapp in which user can click on the map to get lat/long from Google Maps. Is there a code example? I tried googling but only found some

相关标签:
3条回答
  • 2020-12-25 11:49

    You have to use event argument.

     google.maps.event.addListener(map, 'click', function(event) {
         marker = new google.maps.Marker({position: event.latLng, map: map});
         console.log(event.latLng);   // Get latlong info as object.
         console.log( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng()); // Get separate lat long.
     });
    
    0 讨论(0)
  • 2020-12-25 11:50

    The code below will show you how to get the Long and Lat when the user clicks the map - Allow user to place marker on a google map

    google.maps.event.addListener(map, 'click', function( event ){
      alert( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng() ); 
    });
    
    0 讨论(0)
  • 2020-12-25 11:55

    I want to show you complete answere:

    this is main part of the code the event is based on click and get Lat/Long with click and show it at alert()

    google.maps.event.addListener(map, 'click', function(event) { alert(event.latLng.lat() + ", " + event.latLng.lng()); });

    <!DOCTYPE html>
    <html>
    <body>
    <div id="googleMap" style="width:100%;height:400px;"></div>
    
    <script>
    function myMap() {
    var mapProp= {
        center:new google.maps.LatLng(51.508742,-0.120850),
        zoom:5,
    };
    var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
    
    google.maps.event.addListener(map, 'click', function(event) {
    alert(event.latLng.lat() + ", " + event.latLng.lng());
    });
    
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
    </body>
    </html>
    

    please change your API KEY

    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"

    put your API KEY between key= and &callback:

    https://maps.googleapis.com/maps/api/js?key= @@@@@@@ &callback=myMap

    0 讨论(0)
提交回复
热议问题