2015-11-11 114 views
2

的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); 
     }); 
    }); 
} 

結果是,當新的緯度和縱向值輸入到數據庫時,我無法獲得新位置。 我將不勝感激有人可以幫我

+0

經緯度值如何輸入到數據庫? – henrik

+0

就目前而言,我手動輸入然後但在未來的應用將發送該值。 – picador

回答

0

保存上一個經緯度,在一個變量長,並檢查它當你再次問到數據庫。

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) 
    }); 
} 

我想你是要求數據庫調用setMarker方法。

+0

是的,我在我的函數initializeMap()中調用setMarker。 – picador

+0

不過,我想刷新每5秒的網頁,如果是進入了一個新的位置標記應在新的位置 – picador

+0

然後爲最佳的形式給出了使用數據層,使用map.data.loadGeoJson(「HTTP: //..') 方法。每個由ajax方法發送的元素(創建我的函數)都會被渲染,如果元素具有相同的id,則位置會自動更新。 – quindimildev

0

這是使用數據層的溶液。

您可以致電與時刻設定方法服務器:

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

但你必須從服務器發送JSON在GeoJSON格式

{ 
    "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' 
    }); 

});