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
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.
});
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() );
});
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