gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

Google Maps clusterization

We are going to fetch flights data to create our makers. Do not set the map in each marker, the clusterization will set it up instead.

Live demo no longer available.

JavaScript

let $map = document.getElementById("map");
let map = new google.maps.Map(document.getElementById("map"), {
  zoom: 2,
  center: {lat: 36.720426, lng: -4.412573}
});
let markers = [];

// https://opensky-network.org/apidoc/rest.html
fetch('https://opensky-network.org/api/states/all')
  .then(response => {
    if (response.ok) {
      response.json().then(data => {
        // Markers
        data.states.forEach(plane => {
          if (!plane[6] || !plane[5]) return;
          markers.push(new google.maps.Marker({
            position: {lat: plane[6], lng: plane[5]}
          }));
        });
        // Clusterization
        let cluster = new MarkerClusterer(map, markers, {
          imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
        });
      });
    } else $map.textContent = 'Network response was not ok.';
  })
  .catch(error => $map.textContent = 'Fetch error: ' + error);

HTML

<div id="map"></div>

CSS

* {
  padding: 0;
  margin: 0;
}

#map {
  width: 100%;
  height: 100vh;
}
Open in JSFiddle

Tags: AJAX, clusterization, fetch, Google Maps API, map