在谷歌地图上更新JSON中的标记

时间:2015-11-11 12:26:44

标签: javascript python json django google-maps

Django 1.8和python 2.7。 我正在尝试使用jQuery和Ajax更新标记的位置。

我的json对象只有一个数组:

[{"latitud": "55.75222", "ciudad": "Moscu", "longitud": "37.61556"}]

初始化地图后,我创建此功能以设置标记,并且我还使用setTimeout来获取新的标记位置。

function setMarker(map) {

    $.getJSON('http://127.0.0.1:8000/maps/car/gpspos/', function(userPos) {
        userLat = userPos["userPosView"][0].latitud;
        userLon = userPos["userPosView"][0].longitud;
        var position = new google.maps.LatLng(userLat,userLon);
        var marker = new google.maps.Marker({
            position: position,
        });
        marker.setMap(map)


        // A function that checks if the user has a new position and set marker there
        $(document).ready(function(){
            setTimeout(function() {
                (marker.getPosition());
            },5000);
        });
    });
}

结果是,当向db输入新的纬度和纵向值时,我无法获得新位置。 我很感激有人可以帮助我

2 个答案:

答案 0 :(得分:0)

将前一个lat保存在变量中,并在再次询问数据库时进行检查。

var lat, lng;

function setMarker(map) {

    $.getJSON('http://127.0.0.1:8000/maps/car/gpspos/', function(userPos) {
        userLat = userPos["userPosView"][0].latitud;
        userLon = userPos["userPosView"][0].longitud;
        if(lat == null){ lat = userLat; }
        if(lng == null){ lng = userLat; }
        if(userLat != lat && userLon != lng){
            lat = userLat;
            lng = userLong;

            //do stuff
            Console.log("lat lng changed");
        }
        var position = new google.maps.LatLng(userLat,userLon);
        var marker = new google.maps.Marker({
            position: position,
        });
        marker.setMap(map)
    });
}

我猜你要求db调用setMarker方法。

答案 1 :(得分:0)

这是使用数据层的解决方案。

您可以使用setTime方法调用服务器:

var geoUrl = 'http://127.0.0.1:8000/maps/car/gpspos/';
$(document).ready(function(){
    setTimeout(function() {
        map.data.loadGeoJson(geoUrl);
    },5000);
});

但是你必须以GeoJSON格式从服务器发送json

{
    "type": "FeatureCollection",
    "features": [
    {
        "type": "Feature",
        "id": 2
        "geometry": {
            "type": "Point",
            "coordinates": [125.6, 10.1]
        },
        "properties": {
            "name": "Dinagat Islands",
            "ciudad": "Moscu"
        }
    }
]
}

在第二次调用服务器时,每个功能都会被其ID更新,因此如果在服务器端更改了位置,则位置会发生变化。

您还可以使用此方法更改样式,该方法针对绘制的每个要素调用。或者您可以获得该功能的属性

map.data.setStyle(function(feature){
  //getting property
  var ciudad = feature.getProperty('ciudad');

  //setting style for each feature
  return({
      icon: '//example.com/path/to/image.png',
      fillColor: 'green'
  });

});
相关问题