每x秒更新一次Google地图上的标记 [英] Update marker on google map every x seconds

查看:55
本文介绍了每x秒更新一次Google地图上的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据AJAX调用返回的数据每隔x秒更新google map上的标记.每x秒调用一次Ajax函数,但未显示标记.以下是我编写的JavaScript.有人知道原因吗?谢谢.

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>

推荐答案

假定请求按预期运行并返回有效的JSON:

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

google.maps.LatLng 期望参数以纬度,经度的顺序而不是经度,纬度的顺序.

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

此外:最好不要创建每个标记,而是使用 setPosition()更新位置,而不是在每个请求上创建新标记.

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

另外:为确保标记在视口内可见,还可以将地图的中心设置为 latlng

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

这篇关于每x秒更新一次Google地图上的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆