使用JSON每隔x秒更新传单标记位置 [英] Updating Leaflet Marker Position Every x Seconds with JSON

查看:91
本文介绍了使用JSON每隔x秒更新传单标记位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的地图上有一个标记,代表国际空间站的当前位置(来自 http://open-notify-api.herokuapp.com/iss-now.json?callback= ?)。我也试图让它每1秒移动一次跟随该站的轨道。

I have a marker on my map representing the current location of the International Space Station (pulled from http://open-notify-api.herokuapp.com/iss-now.json?callback=?). I'm also trying to get it to move every 1 second to follow along with the station's orbit.

这是我现在的代码:

$.getJSON('http://open-notify-api.herokuapp.com/iss-now.json?callback=?', function(data) {                 
               var latitude = data["data"]["iss_position"]["latitude"];
               var longitude = data["data"]["iss_position"]["longitude"];
               var iss = L.marker([latitude,longitude]).bindPopup("I am the ISS").addTo(map);
               $(function() {
                 setInterval(function() {
                    iss.setLatLng([latitude,longitude]).update();
                 },1000);
               });
              });

以下是jsFiddle中的所有内容: http://jsfiddle.net/zmkqu/

Here's everything in a jsFiddle: http://jsfiddle.net/zmkqu/

似乎在加载时将标记放在正确的位置,但不应该每秒更新一次。关于我做错了什么提示?

It seems to place the marker in the correct position on load, but does not update every second as it should be. Any tips on what I'm doing wrong?

谢谢!

推荐答案

您应该将整个Ajax调用放在 setInterval 回调中。现在您将标记设置为非常相同的位置,因为 data 不会更改。你必须每秒拨打一个新电话:

You should put the whole Ajax call inside the setInterval callback. Right now you are setting the marker to the same position very second, because data does not change. You have to make a new call every second:

var iss;

function update_position() {
    $.getJSON('http://open-notify-api.herokuapp.com/iss-now.json?callback=?', function(data) {
        var latitude = data["iss_position"]["latitude"];
        var longitude = data["iss_position"]["longitude"];
        if (!iss) {
            iss = L.marker([latitude,longitude]).bindPopup("I am the ISS").addTo(map);
        }
        iss.setLatLng([latitude,longitude]).update();
        setTimeout(update_position, 1000);
    });
}

update_position();

DEMO

注意:最好使用 setTimeout 与Ajax调用一起,因为您不知道获取响应需要多长时间。

Note: It's better to use setTimeout together with Ajax calls, since you don't know how a long it takes to get the response.

这篇关于使用JSON每隔x秒更新传单标记位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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