我正在用标记做地图。我从获取谷歌api网址获得了地理坐标数据。但对于标记,我需要来自其他地方的其他信息。是否可以将此附加信息附加到我从获取URL获得的响应中?非常感谢!
代码:
var location = "Seattle";
var username = "Test user";
var time = "8th March 2017";
function toMap(location, username, time) {
if (location.length > 0) {
var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
fetch(googleURL)
.then(function(response) {
// Can I add "location", "username", and "time" to the response result here
// before returning it?????
return response.json();
})
.then(addMarker);
}
}
答案 0 :(得分:1)
Body.json()
json()
mixin的Body
方法需要aResponse
流并将其读取完成。它返回一个承诺 使用包含JSON数据的对象文字解析。
您可以将.then()
链接到.json()
,.then()
处理程序调用集属性,javascript
普通对象的值,return
对象作为参数
fetch(googleURL)
.then(function(response) {
// Can I add "location", "username", and "time" to the response result here
// before returning it?????
return response.json().then(function(json) {
json.location = "abc";
json.username = "def";
json.time = 123;
return json;
});
})
.then(addMarker);
答案 1 :(得分:1)
由于response.json()
会返回Promise
Object
,因此您可以在另一个then()
回调中执行此操作。
var location = "Seattle";
var username = "Test user";
var time = "8th March 2017";
function toMap(location, username, time) {
if (location.length > 0) {
var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
fetch(googleURL)
.then(function(response) {
return response.json();
})
.then(function(json) {
json.location = location;
json.username = username;
json.time = time;
return json;
})
.then(addMarker);
}
}
答案 2 :(得分:0)
当然,您可以将任何字段添加到响应对象
让我们说
fetch(googleURL)
.then(function(response) {
//set these values to anything
response.location = "";
response.username = "";
response.time = "";
return response.json();
})
.then(addMarker);