简体   繁体   中英

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?

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);

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM