我有一个以json格式获取数据的函数。为了在google maps api中显示标记,我创建了一个for循环来从json获取值并将它们设置在marker变量中。我尝试使用if语句只初始化Marker一次。
function setMarker() {
$.getJSON('http://127.0.0.1:8000/locator/car/gpspos/', function(car_pos) {
for (i = 0; i < car_pos["json_data_list"].length; i++){
if (i==0){
marker [i] = new google.maps.Marker({
map: map,
});
userLat = car_pos["json_data_list"][i].latitude;
console.log(userLat);
userLon = car_pos["json_data_list"][i].longitude;
console.log(userLon);
var position = new google.maps.LatLng(userLat,userLon);
marker.setPosition(position);
map.setCenter(position);
}
else {
userLat = car_pos["json_data_list"][i].latitude;
console.log(userLat);
userLon = car_pos["json_data_list"][i].longitude;
console.log(userLon);
var position = new google.maps.LatLng(userLat,userLon);
marker.setPosition(position);
map.setCenter(position);
}
}
});
}
如果sombody可以帮助我使用for循环和if语句,我将不胜感激。
答案 0 :(得分:1)
您不需要检查来初始化标记,您必须为JSON中的每个项目制作标记。
function setMarker() {
$.getJSON('http://127.0.0.1:8000/locator/car/gpspos/', function(car_pos) {
var marker = []; // don't forget the var keyword for local variables
for (var i = 0; i < car_pos["json_data_list"].length; i++){ // same var keyword
marker [i] = new google.maps.Marker({
map: map
});
var userLat = car_pos["json_data_list"][i].latitude; // same var keyword
console.log(userLat);
var userLon = car_pos["json_data_list"][i].longitude; // same var keyword
console.log(userLon);
var position = new google.maps.LatLng(userLat,userLon);
marker[i].setPosition(position); // marker[i] instead of marker
map.setCenter(position);
// the map will be centered on the last marker added to the list.
}
});
}