ArticleZip > Google Maps Js Api V3 Simple Multiple Marker Example

Google Maps Js Api V3 Simple Multiple Marker Example

Google Maps JavaScript API (Application Programming Interface) offers a powerful tool for developers to integrate interactive maps into web applications. In this guide, we'll walk you through a simple example of adding multiple markers to a map using Google Maps JavaScript API v3. This tutorial aims to help beginners grasp the basics of working with JavaScript and the Google Maps API to display multiple markers on a map.

To get started with this example, you'll need to include the Google Maps JavaScript API script in your HTML file or project. You can easily do this by adding the following line within the head tag of your HTML file:

Plaintext

Remember to replace `YOUR_API_KEY` with your actual Google Maps API key obtained from the Google Cloud Platform console.

The next step is to create a simple HTML file with a div element that will hold the map. You can use the following code snippet as a template:

Html

<title>Multiple Markers Example</title>


  <div id="map" style="height: 400px"></div>
  
    function initMap() {
      // Create a map object and specify the DOM element for display.
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 40.7128, lng: -74.0060},
        zoom: 10
      });

      // Define the locations for the markers
      var locations = [
        {lat: 40.7128, lng: -74.0060, title: 'New York City'},
        {lat: 34.0522, lng: -118.2437, title: 'Los Angeles'},
        {lat: 41.8781, lng: -87.6298, title: 'Chicago'}
      ];

      // Add multiple markers to the map
      locations.forEach(function(location) {
        var marker = new google.maps.Marker({
          position: {lat: location.lat, lng: location.lng},
          map: map,
          title: location.title
        });
      });
    }

In this example, we first create a map object centered on a specific location. We then define an array of locations with latitude, longitude, and title for each marker. Finally, we loop through the locations array and add markers to the map for each location.

After setting up the HTML file, open it in a web browser, and you should see a map displaying multiple markers at the specified locations.

By following this straightforward example, you can start exploring the functionalities offered by Google Maps JavaScript API v3 for adding multiple markers to your web applications. Feel free to modify the code and experiment with additional features provided by the API to enhance your mapping projects.

Remember to refer to the official Google Maps JavaScript API documentation for more advanced features and customization options. Happy mapping!