Google Map v3 auto refresh Markers only

I use Google Maps V3 to display some contacts. I want to update markers without affecting where you are on the map or zoom level. I want tokens to be updated every x seconds.

How can I do it? I don't have that much experience with jQuery / ajax.

Below is a working example of my card.

http://jsfiddle.net/dLWNc/

var locations = [ ['some random info here', -37.8139, 144.9634, 1], ['some random info here', 46.0553, 14.5144, 2], ['some random info here', -33.7333, 151.0833, 3], ['some random info here', 27.9798, -81.731, 4], ]; var map = new google.maps.Map(document.getElementById('map_2385853'), { zoom: 1, maxZoom: 8, minZoom: 1, streetViewControl: false, center: new google.maps.LatLng(40, 0), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } 

thanks

+7
source share
1 answer

Well, I have something working - pretty much hard refactoring your source code - you'll recognize various pieces.

 $(function() { var locations = {};//A repository for markers (and the data from which they were constructed). //initial dataset for markers var locs = { 1: { info:'11111. Some random info here', lat:-37.8139, lng:144.9634 }, 2: { info:'22222. Some random info here', lat:46.0553, lng:14.5144 }, 3: { info:'33333. Some random info here', lat:-33.7333, lng:151.0833 }, 4: { info:'44444. Some random info here', lat:27.9798, lng:-81.731 } }; var map = new google.maps.Map(document.getElementById('map_2385853'), { zoom: 1, maxZoom: 8, minZoom: 1, streetViewControl: false, center: new google.maps.LatLng(40, 0), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var auto_remove = true;//When true, markers for all unreported locs will be removed. function setMarkers(locObj) { if(auto_remove) { //Remove markers for all unreported locs, and the corrsponding locations entry. $.each(locations, function(key) { if(!locObj[key]) { if(locations[key].marker) { locations[key].marker.setMap(null); } delete locations[key]; } }); } $.each(locObj, function(key, loc) { if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined) { //Marker has not yet been made (and there enough data to create one). //Create marker loc.marker = new google.maps.Marker({ position: new google.maps.LatLng(loc.lat, loc.lng), map: map }); //Attach click listener to marker google.maps.event.addListener(loc.marker, 'click', (function(key) { return function() { infowindow.setContent(locations[key].info); infowindow.open(map, locations[key].marker); } })(key)); //Remember loc in the `locations` so its info can be displayed and so its marker can be deleted. locations[key] = loc; } else if(locations[key] && loc.remove) { //Remove marker from map if(locations[key].marker) { locations[key].marker.setMap(null); } //Remove element from `locations` delete locations[key]; } else if(locations[key]) { //Update the previous data object with the latest data. $.extend(locations[key], loc); if(loc.lat!==undefined && loc.lng!==undefined) { //Update marker position (maybe not necessary but doesn't hurt). locations[key].marker.setPosition( new google.maps.LatLng(loc.lat, loc.lng) ); } //locations[key].info looks after itself. } }); } var ajaxObj = {//Object to save cluttering the namespace. options: { url: "........",//The resource that delivers loc data. dataType: "json"//The type of data tp be returned by the server. }, delay: 10000,//(milliseconds) the interval between successive gets. errorCount: 0,//running total of ajax errors. errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease. ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker); get: function() { //a function which initiates if(ajaxObj.errorCount < ajaxObj.errorThreshold) { ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay); } }, fail: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); ajaxObj.errorCount++; } }; //Ajax master routine function getMarkerData() { $.ajax(ajaxObj.options) .done(setMarkers) //fires when ajax returns successfully .fail(ajaxObj.fail) //fires when an ajax error occurs .always(ajaxObj.get); //fires after ajax success or ajax error } setMarkers(locs);//Create markers from the initial dataset served with the document. //ajaxObj.get();//Start the get cycle. // ******************* //test: simulated ajax /* var testLocs = { 1: { info:'1. New Random info and new position', lat:-37, lng:124.9634 },//update info and position and 2: { lat:70, lng:14.5144 },//update position 3: { info:'3. New Random info' },//update info 4: { remove: true },//remove marker 5: { info:'55555. Added', lat:-37, lng:0 }//add new marker }; setTimeout(function() { setMarkers(testLocs); }, ajaxObj.delay); */ // ******************* }); 

At the bottom of the code you will find the testLocs , demonstrating the range of options for adding / removing / updating tokens after applying the original dataset.

I did not fully test ajax, but simulated it using the testLocs .

See DEMO

After 10 seconds, the testLocs value will be applied and you will see various changes in the markers (and the information displayed in the infowindow). Please note in particular that these updates do not have to be complete - just indicate the changes.

You will need to configure for your server:

  • create the source dataset following the locs example.
  • return JSON-encoded datasets, following the general format of my testLocs example.

EDIT 1

I have included all the client-side code needed to get the new datasets. All you have to do is:

  • create the server side of the script (for example, "get_markers.php"), which returns the json encoded data set in the correct format (as it was already interrupted).
  • edit the line url: "........", to indicate the server side of the script, for example url: "get_markers.php" .
  • activate the cyclic ajax process by uncommenting the line ajaxObj.get(); .
  • make sure the "simulated ajax" code block is commented out or deleted.

EDIT 2

I added a logical "behavioral switch" named auto_remove . If set to True, a small additional block of code will be launched, as a result of which all tokens for unregistered locations will be deleted.

This will allow you to report all active markers at each iteration. Deletions will occur automatically, without the need to actively command them.

The code that responds to { remove: true } is still in place, so (with auto_remove set to false ), removal can be explicitly set if you ever need to.

Updated DEMO

EDIT 3

The PHP script should build an array of the following form:

 <%php $testLocs = array( 'loc1' => array( 'info' => '1. New Random info and new position', 'lat' => 0, 'lng' => 144.9634 ), 'loc2' => array( 'lat' => 0, 'lng' => 14.5144 ), 'loc3' => array( 'info' => '3. New Random info' ), 'loc5' => array( 'info' => '55555. Added', 'lat' => 0, 'lng' => 60 ) ); echo json_encode($testLocs); exit(); %> 

I am not sure if PHP will process digital keys. If not, try the lines, '1' , '2' , etc. It is probably safest to use all keys in an alphabetical prefix, for example. 'loc1' , 'loc2' , etc. Whatever you choose, make sure that the keys in the javascript locs object are of the same type and composition.

+22
source

All Articles