Reputation: 247
I'm having some trouble implementing viewport marker management with the google maps API. The documentation I'm following can be found here:
https://developers.google.com/maps/articles/toomanymarkers#viewportmarkermanagement
The section I'm working with is titled "Viewport Marker Management."
I can follow the code up until this point:
function showMarkers() {
var bounds = map.getBounds();
// Call you server with ajax passing it the bounds
// In the ajax callback delete the current markers and add new markers
}
I have no idea what code I need to use to accomplish the instructions on the commented out lines. I'm currently pulling marker information from a mySQL database if that matters. I'm not sure if I'm missing something or if the google documentation just ins't comprehensive enough. Any help in appreciated!
Upvotes: 2
Views: 2504
Reputation: 22490
I will give you an example using jQuery.ajax()
, PHP and MySQL, assuming that's what you are using.
Basically, you need to listen for the bounds_changed
event of the map, send the map bounds to your backend, query the database with the bounds, return the correct markers, clear the markers from the map and update it with the new markers.
Here is an example JS code:
var markers = [];
function showMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
var bounds = map.getBounds();
// Call you server with ajax passing it the bounds
// In the ajax callback delete the current markers and add new markers
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
$.ajax({
url: 'your_backend_page.php',
cache: false,
data: {
'fromlat': southWest.lat(),
'tolat': northEast.lat(),
'fromlng': southWest.lng(),
'tolng': northEast.lng()
},
dataType: 'json',
type: 'GET',
async: false,
success: function (data) {
if (data) {
$.each(data, function (i, item) {
createMarker(item);
});
}
}
});
}
function createMarker(item) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.lat, item.lng),
map: map,
draggable: false
});
markers.push(marker);
marker.setMap(map);
}
Then in your backend page, query your database with the parameters (fromlat, tolat, etc.) and echo json_encode();
the results.
Call the showMarkers()
function from the bounds_changed
map event listener. Refer to the documentation if you don't know about event listeners.
Code is untested but you get the idea!
Upvotes: 2