Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

Add markers to Google Map when navigate the map

I have a lot of markers (around 3000) in Google Map and they are with icon and advanced details in popup. That is why, map opens very late, also all markers load very late. Because I load all markers list from database and display them with foreach loop in one time.

Now I think to load markers part by part when navigate (slide) the map.

For example, if I am in Region1, I can see markers only in Region1, when I navigate (slide) the map to Region2, to load only markers in Region2

Please, any ideas, sample or link for this. Does Google Maps API has navigate events?

Upvotes: 1

Views: 1368

Answers (3)

user2622729
user2622729

Reputation: 321

The google website has a page dedicated to this issue with different approaches to improve performance: https://developers.google.com/maps/articles/toomanymarkers

The chapter "Viewport Marker Management" in particular should contain some useful information about how to implement what you describe.

Upvotes: 2

Dr.Molle
Dr.Molle

Reputation: 117364

You may request the marker-details based on the bounds of the map on demand from the DB(e.g. on bounds_changed) .

Optimally your DB should support spatial queries(but it's not required)

Upvotes: 2

Barry Beerman
Barry Beerman

Reputation: 303

You can register map events for center and zoom level changes then load markers if they are in the current viewport:

function loadMarker() {
    // Get the center lat/lng of the map
    var center = map.getCenter();

    // Get the size of the map viewport
    var bounds = map.getBounds(), 
    var cor1 = bounds.getNorthEast(), 
    var cor2 = bounds.getSouthWest(), 
    var cor3 = new google.maps.LatLng(cor2.lat(), cor1.lng()), 
    var cor4 = new google.maps.LatLng(cor1.lat(), cor2.lng()), 
    var width = spherical.computeDistanceBetween(cor1,cor3), 
    var height = spherical.computeDistanceBetween( cor1, cor4);

    // Loop through your markers
    for(var i=0; i < <size of your marker array>; i++) {
        // Get the distance between the center of the map and your markers
        var distanceFromMarker = google.maps.geometry.spherical.computeDistanceBetween(center, <marker lat/lng>);

        if(distanceFromMarker <= width || distanceFromMarker <= height) {
            <load marker>
        }
    }
}

// Register center and zoom level change events
google.maps.event.addListener(map, 'center_changed', loadMarker);
google.maps.event.addListener(map, 'zoom_changed', loadMarker);

Upvotes: 5

Related Questions