这是服务器返回的响应:
使用Google提供的基本反向地理编码
<script>
function geocodelatLng(){
var response = [
{
"address": "213 Marlon Forks\nSouth Corineland, HI 81723-1044",
"lat": "10.30431500",
"lng": "123.89035500"
},
{
"address": "1291 Stephania Road\nLake Dorotheastad, TN 82682-76",
"lat": "10.30309100",
"lng": "123.89154500"
},
{
"address": "20330 Schmeler Course Apt. 210\nNorth Ari, NV 70048",
"lat": "10.30356400",
"lng": "123.89964100"
}
] ;
return _.map(response,coords => {
// console.log(arr.index);
var geocoder = new google.maps.Geocoder;
var latLng = {
lat : parseFloat(coords.lat),
lng : parseFloat(coords.lng)
} ;
// for every lat,lng .
// console.log(latLng);
geocoder.geocode({'location': latLng},function (results,status){
if (status === 'OK') {
if (results[0]) {
console.log(results[0].formatted_address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}); }
这有效,它在控制台中登录了3个地理编码的地址。但是,当我将其与此包一起使用时。这是我的代码,不起作用。
geocodedAddress(){
let geocoder = new google.maps.Geocoder();
let theLocations = this.locations ;
return _.map(theLocations, addr => {
var geocoder = new google.maps.Geocoder();
var locationss = {
lat : parseFloat(addr.lat),
lng : parseFloat(addr.lng)
} ;
// var sampleLocation = { lat: 1.39, lng: 103.8 };
return new Promise(function(resolve, reject) {
geocoder.geocode({'location': locationss }, function(results, status){
if (status === 'OK') {
if (results[0]) {
return results[0].formatted_address;
} else {
console.log(status);
window.alert('No results found');
}
}
})
});
});
}
在我的模板中:
<v-list-tile-content>
<v-list-tile-title v-text="geocodedAddress"></v-list-tile-title>
<v-list-tile-sub-title>{{ address.address }}</v-list-tile-sub-title>
</v-list-tile-content>
您能帮我处理我的代码吗?因为我很难过。
答案 0 :(得分:0)
geocodedAddress
是异步的,您不能在HTML模板中使用它。
您应该创建一个数据属性(例如formatedAddresses
)来存储异步请求的结果
data() {
return {
locations: [],
formatedAddresses: []
}
},
created() {
// for example, you can call it in created hooks
this.geocodedAddress()
},
methods: {
geocodedAddress() {
var self = this;
let geocoder = new google.maps.Geocoder();
let theLocations = this.locations ;
return Promise.all(_.map(theLocations, addr => {
var geocoder = new google.maps.Geocoder();
var locationss = {
lat : parseFloat(addr.lat),
lng : parseFloat(addr.lng)
} ;
// var sampleLocation = { lat: 1.39, lng: 103.8 };
return new Promise(function(resolve, reject) {
geocoder.geocode({'location': locationss }, function(results, status){
if (status === 'OK') {
if (results[0]) {
return results[0].formatted_address;
} else {
console.log(status);
window.alert('No results found');
return null
}
}
})
});
})).then(data => {
console.log(data)
this.formatedAddresses = data
})
}
}
和在模板中
<div v-for="address in formatedAddresses" :key="address">{{ address }}</div>