Find Location by Latitude and Longitude using Google Maps JavaScript
To find a location by latitude and longitude using Google Maps JavaScript API, you can follow the steps below:
- Create an HTML file and include the necessary JavaScript libraries:
- Next, add a div element to the body where the map will be displayed:
- Then, add JavaScript code to initialize the map and find the location using latitude and longitude:
- Finally, call the initMap function to initialize the map when the page loads:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
</head>
<body>
</body>
</html>
<div id="map" style="width: 400px; height: 400px;"></div>
<script>
function initMap() {
// Latitude and longitude of the location
var latitude = 37.7749;
var longitude = -122.4194;
// Create a map object and specify the DOM element for display
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: latitude, lng: longitude},
zoom: 8
});
// Create a marker and set its position
var marker = new google.maps.Marker({
map: map,
position: {lat: latitude, lng: longitude},
title: 'My Location'
});
}
</script>
<script>
// Call the initMap function when the page loads
google.maps.event.addDomListener(window, 'load', initMap);
</script>
Replace “YOUR_API_KEY” in the script tag with your actual Google Maps API key. You can obtain an API key by creating a project in the Google Cloud Console and enabling the Google Maps JavaScript API.
This example creates a map with a marker at the specified latitude and longitude. You can customize the map and the marker according to your needs. The map is displayed in the div element with the id “map”. Adjust the width and height of the div to fit your desired size.
By using the latitude and longitude values of a specific location, you can find and display that location on a map using Google Maps JavaScript API.