I want to use the Bing Maps API to get the coordinates of a location or an address using Javascript.
I generated the request as follows: http://dev.virtualearth.net/REST/v1/Locations?CountryRegion=DE&locality=Munich&addressLine=1%20Schloss%20Nymphenburg&maxResults=1&key={myKEY}
When I open manually the link, I see a JSON-File like this:
But how can I fetch this file, to get the coordinates?
I tried the following code, to show the data on the console, but nothing happens.
var req = new Request(request); fetch(req).then(function(response) { return response.text(); }).then(function(text) { console.log(text); });
Do I have to import special libraries or is it just the wrong way of doing it?
let data = fetch('http://dev.virtualearth.net/REST/v1/Locations?CountryRegion=DE&locality=Munich&addressLine=1%20Schloss%20Nymphenburg&maxResults=1&key=%7BmyKEY%7D').then(response => console.log("res: ", response)).catch(err => console.log("err: ", err)); console.log(data) //console.log(data["resourceSssSets"]["0"]["resources"]["0"]["point"]["coordinates"]) /* { "resourceSssSets":{ "0": { "resources":{ "0":{ "point":{ "coordinates": { "0": "", "1": "" } } } } } } } */
the result you have is in the following form
{
"resourceSssSets":{
"0": {
"estimatedTotal": 1,
"resources" :{
"0" :{
"__type" : "location....",
"bbox" {
"0": "000",
"1": "000",
"3": "000",
"4": "0000",
"name": "name"
},
"point":{
"type": "point",
"coordinates": {
"0": "",
"1": ""
},
"address": {
}
}
}
}
}
}
}
A json array now it's up to you to see what you want to collect
Here is how to you would make the request and process the result:
var req = 'http://dev.virtualearth.net/REST/v1/Locations?CountryRegion=DE&locality=Munich&addressLine=1%20Schloss%20Nymphenburg&maxResults=1&key={yourKey}';
fetch(req)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(JSON.stringify(data));
if(data.resourceSets && data.resourceSets.length > 0 && data.resourceSets[0].resources && data.resourceSets[0].resources.length > 0){
var firstResult = data.resourceSets[0].resources[0];
var latitude = firstResult.point.coordinates[0];
var longitude = firstResult.point.coordinates[1];
//Do something with this data.
}
})
Note I'm passing in the URL as a string, and am calling response.json() instead of response.text()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.