Get lattitude and longitude onmouseover and onclick event in google map v3
As you move the mouse over the google map you can see the lattitude and longitude displayed below the google map.
When you click on google map the lattitude and longitude of the mouse position is displayed in the text box below the google map.
This example is very simple so you can just view the source code to copy and use it. anyway i have explained below.
Lattitude:
Longitude:
Lat Lng:
Lat Lng on click:
Code and Explanation
You can also copy this code by viewing the source code of this page
var map; function mapa() { var opts = {'center': new google.maps.LatLng(26.12295, -80.17122), 'zoom':11, 'mapTypeId': google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById('mapdiv'),opts); google.maps.event.addListener(map,'click',function(event) { document.getElementById('latlongclicked').value = event.latLng.lat() + ', ' + event.latLng.lng() }) google.maps.event.addListener(map,'mousemove',function(event) { document.getElementById('latspan').innerHTML = event.latLng.lat() document.getElementById('lngspan').innerHTML = event.latLng.lng() document.getElementById('latlong').innerHTML = event.latLng.lat() + ', ' + event.latLng.lng() }); }
- First an object representing google map properties is created with zoom level, map center and map type.
- Then a map object is created. It takes two parameters. One is the div where the map should be displayed and the other is the object which contains various properties to initialize the google map.
- With the above to lies the map can be displayed.
- Next are the two event handlers which will display the lattitude and longitude when the move is moved over the google map or when the mouse is clicked on the map.
- The event listener needs three parameters first is the map object, next is the event like onmousemove or onclick and the third parameter is the callback function to which the coordinates are passed as a parameter.
- Each time the event handlers (callback functions) are called i am updating the lattitude and longitude.
Comments, Suggestions, Objections, ...