【问题标题】:Update marker on google map every x seconds每 x 秒更新一次谷歌地图上的标记
【发布时间】:2014-02-02 01:10:57
【问题描述】:

我正在尝试根据 AJAX 调用返回的数据每 x 秒更新一次谷歌地图上的标记。每 x 秒调用一次 Ajax 函数,但不显示标记。下面是我写的 JavaScript。有人知道原因吗?谢谢。

    <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>

【问题讨论】:

    标签: javascript ajax google-maps google-maps-api-3


    【解决方案1】:

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

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

    google.maps.LatLng 期望参数的顺序是 latitude, longitude ,而不是 longitude,latitude

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

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

    【讨论】:

      【解决方案2】:

      尝试使用 javascript 来提醒带有新标记位置的消息,以查看它是否真的在后台更新。如果它剂量,那么它与刷新dom或其他东西有关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 2020-09-01
        • 1970-01-01
        • 2012-02-21
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多