Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps HTML5 click to get lat, long

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 website that does that but no soucecode example.

This is because I'm going to use HTML5 geolocation to display the current location first, but if it's not accurate then users can specify that by themselves.

Thanks a lot.

like image 453
toy Avatar asked Nov 06 '11 12:11

toy


2 Answers

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() ); 
});
like image 83
LiamB Avatar answered Oct 13 '22 05:10

LiamB


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

like image 6
m-tech Avatar answered Oct 13 '22 04:10

m-tech