To pass latitude and longitude dynamically to Google Maps using JavaScript, you can follow these steps:
- First, create a div element in your HTML where you want to display the map.
- Next, create a JavaScript function that will create and initialize the map:
- Within the initMap function, you need to provide the latitude and longitude as parameters.
- Call the initMap function with the desired latitude and longitude values:
- The above line of code will initialize the map with the latitude of 40.7128 and longitude of -74.0060. You can replace these values with your own dynamically retrieved values.
- Add the Google Maps API script in your HTML file:
- Replace YOUR_API_KEY with your own Google Maps API key. You can get an API key by creating a project in the Google Cloud Console and enabling the Maps JavaScript API.
- Finally, add the div element in your HTML where you want to display the map:
function initMap(latitude, longitude) {
var options = {
zoom: 10,
center: { lat: latitude, lng: longitude }
};
var map = new google.maps.Map(document.getElementById("map"), options);
}
initMap(40.7128, -74.0060);
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
<div id="map" style="width: 100%; height: 400px;">
The above div with id "map" will be used by the JavaScript function to render the map dynamically.
Here's an example that demonstrates the above steps:
Dynamic Google Maps
Related Post