Home > Web Front-end > JS Tutorial > How to Easily Implement Multiple Markers with InfoWindows on a Google Map using JavaScript?

How to Easily Implement Multiple Markers with InfoWindows on a Google Map using JavaScript?

DDD
Release: 2024-12-31 04:22:09
Original
902 people have browsed it

How to Easily Implement Multiple Markers with InfoWindows on a Google Map using JavaScript?

Simple Google Maps Multiple Marker Implementation in JavaScript

In this tutorial, we will explore a simplified approach to creating multiple markers on a Google Map.

Overview

For beginners exploring the Google Maps API, it can seem complex to plot multiple markers on a map. This tutorial provides a simple and straightforward solution.

Example Data

Let's use Google's sample data array:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  // ... Additional beach locations
];
Copy after login

Creating the Map

First, we initialize a Google Map:

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: { lat: -33.92, lng: 151.25 },
  mapTypeId: google.maps.MapTypeId.ROADMAP
});
Copy after login

Creating Markers

To create multiple markers, we iterate through the locations array:

var marker, i;
for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    position: { lat: locations[i][1], lng: locations[i][2] },
    map: map
  });
}
Copy after login

Adding Pop-up InfoWindows

We create an InfoWindow for each marker to display the beach name when clicked:

var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    infowindow.setContent(locations[i][0]);
    infowindow.open(map, marker);
  }
})(marker, i));
Copy after login

Complete Result

The full code snippet below includes all the elements needed for the multiple marker functionality:

// HTML with map container
<!DOCTYPE html>
<html> 
<head> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY" 
          type="text/javascript"></script>
</head> 
<body>
  <div>
Copy after login

By following these steps, you can easily plot multiple markers with pop-up InfoWindows on a Google Map.

The above is the detailed content of How to Easily Implement Multiple Markers with InfoWindows on a Google Map using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template