12

Here is my code(most code from Google's API page).

<script>
    var beaches = [
      ['Bondi Beach', -12.890542, 120.274856, 4],
      ['Coogee Beach', -12.923036, 520.259052, 5],
      ['Cronulla Beach', -12.028249, 1221.157507, 3],
      ['Manly Beach', -12.80010128657071, 1121.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 121.259302, 1]
    ];

    function setMarkers(map, locations) {
      for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: beach[0],
            zIndex: beach[3]
        });
      }
    }

    function initialize() {
      var mapOptions = {
        zoom: 3,
        center: new google.maps.LatLng(38.77417, -9.13417),
        mapTypeId: google.maps.MapTypeId.SATELLITE
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'),
                                    mapOptions);

      setMarkers(map, beaches);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    setInterval(function() { setMarkers(map, beaches); }, 5000);

</script>

What I simply want to do is reload only the markers. I tried reloading the map using initialize function but it didn't work. Then I tried to reloading using setMarkers function and still no luck...

Thanks for your help.

3
  • 1
    Why do you want to reload the markers?
    – putvande
    Mar 31, 2014 at 23:40
  • Change the position of them in the map. The idea is get data from MySQL DB which is updated every 5 minutes and then show locations in Google Maps.
    – Fred
    Apr 1, 2014 at 0:17
  • 5
    Do you think -12.80010128657071, 1121.28747820854187 are valid lat/lng coordinates?
    – MrUpsidown
    Oct 16, 2014 at 15:09

4 Answers 4

42
+25

Few things you should do / things that I have changed from your original code:

  1. Use valid lat/lng coordinates for your markers (1121.28747820854187 for example is not a valid lng)
  2. Create a global variable for your map (easier to reference in your script)
  3. Create an array to hold your markers
  4. I have added a marker animation animation: google.maps.Animation.DROP, to your markers, so that you can see when they are reloaded, and a reload markers button to call the reload function.

Basically what you want to do is:

  1. Create each marker within the setMarkers function
  2. Push each marker to the markers array
  3. When reloading your markers, loop through your markers array and call setMap(null) on each marker to remove it from the map
  4. Once done, call setMarkers again to re-draw your markers

Updated code:

var map;
var markers = []; // Create a marker array to hold your markers
var beaches = [
    ['Bondi Beach', 10, 10, 4],
    ['Coogee Beach', 10, 11, 5],
    ['Cronulla Beach', 10, 12, 3],
    ['Manly Beach', 10, 13, 2],
    ['Maroubra Beach', 10, 14, 1]
];

function setMarkers(locations) {

    for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            animation: google.maps.Animation.DROP,
            title: beach[0],
            zIndex: beach[3]
        });

        // Push marker to markers array
        markers.push(marker);
    }
}

function reloadMarkers() {

    // Loop through markers and set map to null for each
    for (var i=0; i<markers.length; i++) {

        markers[i].setMap(null);
    }

    // Reset the markers array
    markers = [];

    // Call set markers to re-add markers
    setMarkers(beaches);
}

function initialize() {

    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(10,12),
        mapTypeId: google.maps.MapTypeId.SATELLITE
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    setMarkers(beaches);

    // Bind event listener on button to reload markers
    document.getElementById('reloadMarkers').addEventListener('click', reloadMarkers);
}

initialize();

Working example:

JSFiddle demo

0
3

To reload the markers, when you create then, push them to an array.

Then create a function where you iterate through the array, setting the markers map as null. After this, erase the array.

Edit: I will assume, you gonna return a JSON with the following structure on your PHP

{
  beaches: [
            [
              "Bondi Beach",
              -12.890542,
              120.274856,
              4
            ],
            [
              "Other Beach",
              -12.890542,
              120.274856,
              5
            ]
           ]
}

I'm also assumming you gonna use jQuery (just to simplify the ajax call and json iteration)

<script>
    var arrMarkers = [];

    var beaches = [
      ['Bondi Beach', -12.890542, 120.274856, 4],
      ['Coogee Beach', -12.923036, 520.259052, 5],
      ['Cronulla Beach', -12.028249, 1221.157507, 3],
      ['Manly Beach', -12.80010128657071, 1121.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 121.259302, 1]
    ];

    function setMarkers(map, locations) {
      for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: beach[0],
            zIndex: beach[3]
        });

        arrMarkers.push(marker);
      }
    }

    function initialize() {
      var mapOptions = {
        zoom: 3,
        center: new google.maps.LatLng(38.77417, -9.13417),
        mapTypeId: google.maps.MapTypeId.SATELLITE
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'),
                                    mapOptions);

      setMarkers(map, beaches);
    }

    function removeMarkers(){
     var i;
     for(i=0;i<arrMarkers.length;i++){
       arrMarkers[i].setMap(null);
     }
     arrMarkers = [];

    }

    google.maps.event.addDomListener(window, 'load', initialize);

    setInterval(function() { 
       updateTheMarkers();
    }, 5000);

    function updateTheMarkers(){
      $.ajax({
      type: "GET",
      url: "/yourphp.php",
              success: function (data) {
                  //We remove the old markers
                  removeMarkers();
                  var jsonObj = $.parseJSON(data),
                      i;

                  beaches =[];//Erasing the beaches array

                  //Adding the new ones
                  for(i=0;i < jsonObj.beaches.length; i++) {
                    beaches.push(jsonObj.beaches[i]);
                  }

                  //Adding them to the map
                  setMarkers(map, beaches);
              }
         });
    }

</script>

Basically, now, every 5 secs your javascript do an ajax request to your php, your php will return an updated json with the new beaches, you will remove the old markers, fill the array with the new locations and generate the new markers.

0
0

This may not be the initial doubt, but to clear the markers and other components of the map, just before loading the map and its components put:

map.clear ();
1
  • 2
    How does that answer the original question? Where is this documented?
    – MrUpsidown
    Mar 7, 2018 at 19:07
-1

even if initially it s set as invisible after setting new location to Marker:

markerLcl.setPosition(mLatLng)

got it redrawn in the new place by:

        markerLcl.setMap(null)
        markerLcl.setMap(mMap)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.