sinsin
sinsin

Reputation: 421

Update marker on google map every x seconds

I am trying to update marker on google map for every x seconds based on the data returned from a AJAX call. The Ajax function is called for every x seconds but the marker is not shown. Below is the JavaScript I wrote. Anyone know the reason? Thanks.

    <script type="text/javascript">
  var map
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(1.32643, 103.79426),
      zoom: 11
    };
  map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
  }


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

        //Ajax call to get position
  function set_center() {
        var feedback = $.ajax({
            type: 'GET',
            url: 'get_gps_position',
          success: function (data) {
            console.log(data);
              if (data['gps_position_longitude'] != null && data['gps_position_latitude'] != null ) {
                var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);
                var marker = new google.maps.Marker({
                position: latlng, 
                map: map,
                title:"Hello World!"});

              };


        },
        error: function(data) {
            $("#result").html(data);
            console.log(data)
        }
    });
  }

  setInterval(set_center, 10000);

</script>

Upvotes: 2

Views: 3890

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117314

Assuming that the request runs as expected and returns a valid JSON:

var latlng = new google.maps.LatLng(data['gps_position_longitude'], data['gps_position_latitude']);

A google.maps.LatLng expects the arguments to be in the order latitude, longitude , not longitude,latitude .

Furthermore: instead of creating new markers on each request you better create a single marker and use setPosition() to update the position.

Additionally: to ensure that the marker is visible inside the viewport also set the center of the map to latlng

Upvotes: 2

JustWe
JustWe

Reputation: 653

Try use javascript to alert a message with the new marker's position to see if it really gets updated in the background. If it dose, then its to do with refreshing the dom or something.

Upvotes: 0

Related Questions