Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map markers not clustering

I have a map which has multiple markers within close proximity of each other. Trying to integrate the marker clustering through google dev kit.

However the clustering is not occuring, and am also not getting an error in console - which makes it somewhat tricky.

Map data being used:

  var places = [{
        "id": 1,
        "name": "Test",
        "coordinate": {
            "latitude": -37.8136,
            "longitude": 144.9630
        },
        "description": "This is a test",
        "is_active": true
    },
    {
        "id": 2,
        "name": "Test2",
        "coordinate": {
            "latitude": -37.8136,
            "longitude": 144.9430
        },
        "description": "This is a test",
        "is_active": true
    },
    {
        "id": 3,
        "name": "Test3",
        "coordinate": {
            "latitude": -37.8136,
            "longitude": 144.9530
        },
        "description": "This is a test",
        "is_active": true
    },
    {
        "id": 4,
        "name": "Test4",
        "coordinate": {
            "latitude": -37.8136,
            "longitude": 144.9670
        },
        "description": "This is a test",
        "is_active": true
    }]

Javascript:

var GoogleMap = {
    map: null,
    markers: {},
    init: function(lat, lng, places) {
        var self = this;
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(lat, lng)
        };
        this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
        this.infowindow = new google.maps.InfoWindow({
            size: new google.maps.Size(50, 50)
        });
        var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
        google.maps.event.addListener(searchBox, 'places_changed', function() {
            searchBox.set('map', null);
            var places = searchBox.getPlaces();
            var bounds = new google.maps.LatLngBounds();
            var i, place;
            for (i = 0; place = places[i]; i++) {
                (function(place) {
                    var marker = new google.maps.Marker({
                        position: place.geometry.location
                    });
                    marker.bindTo('map', searchBox, 'map');
                    google.maps.event.addListener(marker, 'map_changed', function() {
                        if (!this.getMap()) {
                            this.unbindAll();
                        }
                    });
                    bounds.extend(place.geometry.location);
                }(place));
            }
            this.map.fitBounds(bounds);
            searchBox.set('map', map);
            map.setZoom(Math.min(map.getZoom(), 12));
        });
   
        $.each(places, function() {
            self.addMarker(this);
        });
        this.setCenterPoint();
    },
    // Create map markers
    addMarker: function(place) {
        var self = this;
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(place.coordinate.latitude, place.coordinate.longitude),
            map: self.map,
            title: place.name,
            icon: place.image
        });
      
        console.log(place);
        // Create information event for each marker
        marker.info_window_content = 'TEST'
        self.markers[place.id] = marker
        google.maps.event.addListener(marker, 'click', function() {
            self.infowindow.setContent(marker.info_window_content)
            self.infowindow.open(self.map, marker);
        });   
        // cluster the markers using google marker clusterer
       var markerClusterer = new MarkerClusterer(this.map, self.marker, {
      imagePath:
        "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
    });
        
    },
    // Update map markers
    updateMarkers: function(records) {
        var self = this;
        $.each(self.markers, function() {
            this.setMap(null);
        })
        $.each(records, function() {
            self.markers[this.id].setMap(self.map);
        });
        //Set map center
        if (records.length) self.setCenterPoint();
    },
    // Set centre point for map
    setCenterPoint: function() {
        var lat = 0,
            lng = 0;
        count = 0;
        //Calculate approximate center point based on number of JSON entries
        for (id in this.markers) {
            var m = this.markers[id];
            if (m.map) {
                lat += m.getPosition().lat();
                lng += m.getPosition().lng();
                count++;
            }
        }
        if (count > 0) {
            this.map.setCenter(new google.maps.LatLng(lat / count, lng / count));
        }
    }
};
// CHANGE MAP FOCUS:
function showCompany(lat, lng) {
    var position = new google.maps.LatLng(lat, lng);
    map.setCenter(position);
    alert(lat, lng);
}

Which is displaying the map in html via the div ID 'map'.

I have created a JSFiddle to see the map markers being loaded in #map, but as you can see. The markers are loading, but not clustering.

In a desperate attempt to resolve, have also tried changing the default zoom level, as I thought this might be creating the issue.

Link: https://jsfiddle.net/pixelmedia/z1ke9bwq/37/

like image 293
pixelcreated Avatar asked May 21 '21 02:05

pixelcreated


People also ask

What is clustering on a map?

What is Clustering? Clustering allows you, as the map maker, to explore and visualize patterns that would have otherwise been hidden. Quickly see your points aggregated into smaller groupings of points. This provides a better understanding of how many points exist within an area.

How do I remove a marker cluster from Google Maps?

Removing all markers You can then clear all the markers using clearMarkers something like this: markerClusterer. clearMarkers(); markers = [];

How do I cluster markers on a map?

You can use the MarkerClusterer library in combination with the Maps JavaScript API to combine markers of close proximity into clusters, and simplify the display of markers on the map. To see how marker clustering works, view the map below. The number on a cluster indicates how many markers it contains.

How do I combine markers of close proximity into clusters?

You can use the @googlemaps/markerclusterer library in combination with the Maps JavaScript API to combine markers of close proximity into clusters, and simplify the display of markers on the map. To see how marker clustering works, view the map below. The number on a cluster indicates how many markers it contains.

What is the maximum number of markers I can cluster together?

Below is an example of custom marker clusters: The marker clustering utility is part of the Maps SDK for iOS Utility Library. If you haven't yet set up the library, follow the setup guide before reading the rest of this page. For best performance, the recommended maximum number of markers is 10,000.

How do I check if a cluster icon or marker was tapped?

When the user taps a marker, an individual cluster item, or a cluster, the API triggers mapView:didTapMarker: and attaches the extra cluster data to the marker.userData property. You can then check if the userData conforms to the GMUCluster protocol to determine if a cluster icon or a marker was tapped.


1 Answers

Strange that no body reply you with the bounty.

Here is the clustered markers version based on yours:

https://jsfiddle.net/qakbnx6h/1/

The problem is in the addMarker(), for each place, you created a new MarkerClusterer so the clustering is not working.

To solve it:

  1. Remove new MarkerClusterer on addMark()
  2. return the marker from addMaker()
addMarker: function(place) {
    var self = this;
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(place.coordinate.latitude, place.coordinate.longitude),
        map: self.map,
        title: place.name,
        icon: place.image
    });
    
    console.log(place);
    // Create information event for each marker
    marker.info_window_content = 'TEST'
    self.markers[place.id] = marker
    google.maps.event.addListener(marker, 'click', function() {
            self.infowindow.setContent(marker.info_window_content)
            self.infowindow.open(self.map, marker);
            });  

    // return marker; 
    return marker;
},
  1. Push the new marker into a array
  2. Add the new MarkerClusterer below $.each of places and use the array marker created on step 3
// markers array to store place marker
const markers = []
$.each(places, function() {
    // push new marker to array
    markers.push( self.addMarker(this));
});

// use the markers in MarkerClusterer
const markerClusterer = new MarkerClusterer(this.map, markers, {
  imagePath:  "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
like image 143
Mic Fung Avatar answered Oct 19 '22 04:10

Mic Fung