混合应用开发主要应用技术就是H5,H5定位的实现方法也比较广泛,但是定位后如何获取到有用的信息,这个还需要一番研究,本人就遇到过这个问题。
在我的应用已经定位到坐标,需要根据坐标获取国家和城市名,不需要其他信息,但是返回信息中又无法指定。
于是找到下面的方法:
navigator.geolocation.getCurrentPosition(position => {
let addressUrl = 'http://maps.google.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&language=en-US&sensor=false';
this.HttPService.get(addressUrl).then(address => {
let [country, city] = ['', ''];
for (let i=0; i<address.results[0].address_components.length; i++) {
for (let b=0;b<address.results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (address.results[0].address_components[i].types[b] == "locality") {
//this is the object you are looking for
city= address.results[0].address_components[i];
}
if (address.results[0].address_components[i].types[b] == "country") {
//this is the object you are looking for
country= address.results[0].address_components[i];
}
}
}
d.resolve(city.long_name + ',' + country.long_name);
}, error => {
d.reject('time out');
})
}, () => {
d.reject('time out');
}, {timeout: 20000});
代码主要原理就是匹配到”country”,”locality”,对应到的是一个国家,一个城市。