How To Add Multiple Markers On Google Maps Javascript Dynamically

How to add multiple markers on Google Maps JavaScript dynamically

Adding multiple markers dynamically on Google Maps can be achieved using the JavaScript API. Here is an example:

Example:

Assuming you have a div element with id “map” that will be used to display the map:

      
<div id="map" style="width: 100%; height: 500px;"></div>
      
    

And assuming you have an array of marker objects with latitude and longitude information:

      
var markers = [
  { lat: 37.7749, lng: -122.4194 },
  { lat: 34.0522, lng: -118.2437 },
  { lat: 40.7128, lng: -74.0060 }
];
      
    

First, you need to create a script block to hold your JavaScript code:

      
<script>
  // Your JavaScript code goes here
</script>
      
    

Inside the script block, you need to initialize the map:

      
<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 10,
      center: { lat: 37.7749, lng: -122.4194 }
    });
  }
</script>
      
    

Then, you can loop through the “markers” array and create a marker for each object:

      
<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 10,
      center: { lat: 37.7749, lng: -122.4194 }
    });

    for (var i = 0; i < markers.length; i++) {
      var marker = new google.maps.Marker({
        position: { lat: markers[i].lat, lng: markers[i].lng },
        map: map
      });
    }
  }
</script>
      
    

Finally, you need to load the Google Maps JavaScript API and call the initMap function:

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

Make sure to replace “YOUR_API_KEY” with your actual Google Maps API key.

Now, when you load the page, you should see the map with multiple markers.

Read more

Leave a comment