Getting Latitude and Longitude from a Click Event

in Jquery Javascript


When we get the coordinates of a location in the world, we can get a lot of information about it. These include weather information, traffic, economic information, pricing, …

The use of google maps makes it easy to get the coordinates of the place we select by clicking the mouse. You need regist Google Maps API key to use and show maps. The default when opening the maps is the location of Tokyo Japan, the zoom level is 6, of course you can choose another location, the other zoom level depends on the requirements.

 

Get-Lat-Lng-from-click-event

 

1. HTML: Show maps in tags html

<p id=”getLatLng”></p>
<div id=”map”></div>

 

2. CSS: Show maps with css

<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>

 

3. API KEY

You need resigster one API KEY to show map

<script async defer
src=”https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap”>
</script>

 

4. SCRIPT: Display maps

<script>
function initMap() {
// Default in Tokyo Japan
var myLatlng = {lat: 35.67083724108701, lng: 139.76739407395357}; 

        // Ex in Australia: var myLatlng = {lat: -25.363, lng: 131.044};

        var map = new google.maps.Map(
document.getElementById(‘map’), {zoom: 6, center: myLatlng});

        // Create the initial InfoWindow.
var infoWindow = new google.maps.InfoWindow(
{content: ‘Click the map to get Lat/Lng!’, position: myLatlng});
infoWindow.open(map);

        // Configure the click listener.
map.addListener(‘click’, function(mapsMouseEvent) {
// Close the current InfoWindow.
infoWindow.close();

          // Create a new InfoWindow.
infoWindow = new google.maps.InfoWindow({position: mapsMouseEvent.latLng});
infoWindow.setContent(mapsMouseEvent.latLng.toString());
infoWindow.open(map);

          document.getElementById(“getLatLng”).append(mapsMouseEvent.latLng.toString() + ‘ – ‘);
});
}
</script>

 

Download full code at here: Download full code

Tags: , , , , ,

Your comment

Please rate

Your comment is approved before being displayed.
Your email address will not be published. Required fields are marked *


*
*
*