我正在使用以下脚本从我的api加载数据,并在谷歌地图、上显示位置
问题是,当我将来自api的响应分配给本地变量locations
时,它不起作用,浏览器控制台说";无法读取未定义的"的属性"length";
当我手动定义位置时,它工作得很好。
var locations = [{
"_id": "5f3de313b94dd30a984dadcc",
"uname": "sudesh",
"__v": 0,
"lat": 6.903413,
"lng": 79.884888
}];
如何将响应分配给此location
变量
这是我使用的代码
<script>
var locations;
// var locations;
fetch("http://localhost:5000/api/user/getall").then(function(response) {
locations= response;
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function() {
console.log("Booo");
});
/**
* Create new map
*/
var infowindow;
var map;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var purple_icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(6.9271, 79.8612),
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var markers = {};
// console.log(locations);
var getMarkerUniqueId = function(lat, lng) {
return lat + '_' + lng;
};
var getLatLng = function(lat, lng) {
return new google.maps.LatLng(lat, lng);
};
var i;
var confirmed = 0;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map,
icon: locations[i][4] === '1' ? red_icon : purple_icon,
html: "<div>n" +
"<table class="map1">n" +
"<tr>n" +
"<td><a>User:</a></td>n" +
"<td><textarea disabled id='manual_description' placeholder='Description'>" + locations[i].uname + "</textarea></td></tr>n" +
"</table>n" +
"</div>"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow = new google.maps.InfoWindow();
confirmed = locations[i][4] === '1' ? 'checked' : 0;
$("#confirmed").prop(confirmed, locations[i][4]);
$("#id").val(locations[i][0]);
$("#description").val(locations[i][3]);
$("#form").show();
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
API 的回复
[
{
"_id": "5f3de313b94dd30a984dadcc",
"uname": "sudesh",
"__v": 0,
"lat": 6.903413,
"lng": 79.884888
},
{
"_id": "5f3de9d9b94dd30a984e644e",
"uname": "saman",
"__v": 0,
"lat": 6.952149,
"lng": 79.86721
}
]
首先,您需要先解析json,然后分配值所以你的任务应该在第二天,然后是
第二,then
关键字意味着等待某件事完成,然后进行
所以当你做循环时,里面的任何东西都没有运行
循环需要等待api,因此它也应该在当时的闭包中
fetch("http://localhost:5000/api/user/getall").then(function(response) {
return response.json();
}).then(function(data) {
var locations = data;
/**
* Create new map
*/
var infowindow;
var map;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var purple_icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(6.9271, 79.8612),
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var markers = {};
// console.log(locations);
var getMarkerUniqueId = function(lat, lng) {
return lat + '_' + lng;
};
var getLatLng = function(lat, lng) {
return new google.maps.LatLng(lat, lng);
};
var i;
var confirmed = 0;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map,
icon: locations[i][4] === '1' ? red_icon : purple_icon,
html: "<div>n" +
"<table class="map1">n" +
"<tr>n" +
"<td><a>User:</a></td>n" +
"<td><textarea disabled id='manual_description' placeholder='Description'>" + locations[i].uname + "</textarea></td></tr>n" +
"</table>n" +
"</div>"
});
}).catch(function() {
console.log("Booo");
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow = new google.maps.InfoWindow();
confirmed = locations[i][4] === '1' ? 'checked' : 0;
$("#confirmed").prop(confirmed, locations[i][4]);
$("#id").val(locations[i][0]);
$("#description").val(locations[i][3]);
$("#form").show();
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})(marker, i));
}
这里有几个选项:
async function() {
var { res } = await fetch("http://localhost:5000/api/user/getall");
return JSON.parse(res);
}
// OR
function getLocations() {
return new Promise((resolve, reject) => {
var locations = fetch("http://localhost:5000/api/user/getall").then(res => res.json());
locations ? resolve(locations) : reject(null);
});
}
getLocations()
.then(data => {
// loop
})
.catch(err => {
// handle error
});
另外,在循环中使用?
来防止错误
for (i = 0; i < locations?.length; i++) {
// logic
}
Location在promise中被赋值,因此您的循环需要等待,直到它从promise获得响应。
您可以使用异步等待。
或者您可以使用以下
function createNewMap(locations) {
/**
* Create new map
*/
var infowindow;
var map;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var purple_icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(6.9271, 79.8612),
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var markers = {};
// console.log(locations);
var getMarkerUniqueId = function (lat, lng) {
return lat + '_' + lng;
};
var getLatLng = function (lat, lng) {
return new google.maps.LatLng(lat, lng);
};
var i;
var confirmed = 0;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map,
icon: locations[i][4] === '1' ? red_icon : purple_icon,
html: "<div>n" +
"<table class="map1">n" +
"<tr>n" +
"<td><a>User:</a></td>n" +
"<td><textarea disabled id='manual_description' placeholder='Description'>" + locations[i].uname + "</textarea></td></tr>n" +
"</table>n" +
"</div>"
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow = new google.maps.InfoWindow();
confirmed = locations[i][4] === '1' ? 'checked' : 0;
$("#confirmed").prop(confirmed, locations[i][4]);
$("#id").val(locations[i][0]);
$("#description").val(locations[i][3]);
$("#form").show();
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})(marker, i));
}
}
var locations;
// var locations;
fetch("http://localhost:5000/api/user/getall").then(function (response) {
locations = response;
return response.json();
}).then(function (data) {
createNewMap(data);
console.log(data);
}).catch(function () {
console.log("Booo");
});
要了解异步处理,您可以查看一下。