npm install --save @ionic-native/geolocation
import { Geolocation } from '@ionic-native/geolocation';
@NgModule({
providers: [
{ provide: ErrorHandler, useClass: IonicErrorHandler },
Geolocation
]
})
import { Injectable } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation';
@Injectable()
export class GeolocationService {
constructor(
private geolocation: Geolocation
) {}
}
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.1&key=99f20bf360cfecd1eb94acfcb6819474"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>
/**
* 获取当前地理位置
*/
getCurrentPosition(): Promise<{ latitude: string, longitude: string }> {
return this.geolocation.getCurrentPosition().then(res => {
let latitude = res.coords.latitude.toString(); //纬度
let longitude = res.coords.longitude.toString(); //经度
let locations = { latitude: latitude , longitude: longitude };
return Promise.resole(locations );
}).catch(e => {
console.log(e);
return Promise.reject(e);
});
}
将geolocation坐标转为百度地图坐标
import { Injectable } from '@angular/core';
declare var BMap;//声明百度地图
@Injectable()
export class GeolocationService {
/**
* 将经纬度转换为百度地图坐标
* @param latitude 纬度
* @param longitude 经度
*/
transferBaiDuMapLocations(longitude,latitude){
let gpsPoint = new BMap.Point(longitude, latitude);
return BMap.Convertor.translate(gpsPoint, 0, (point) => {
if (point.lat && point.lng) {
return Promise.resolve({ latitude: point.lat, longitude: point.lng });
} else {
return Promise.reject('转换百度坐标失败!');
}
});
}
}
将geolocation坐标转为高德地图坐标
import { Injectable } from '@angular/core';
declare var AMap;//声明高德地图
@Injectable()
export class GeolocationService {
/**
* 高德地图坐标转换
* @param latitude 纬度
* @param longitude 经度
*/
positionTransfer(latitude, longitude){
let latlon = longitude + ',' + latitude;
let url = "https://restapi.amap.com/v3/assistant/coordinate/convert? locations="+latlon+"&coordsys=gps&output=json&key=059b0ae61fe2a851334e9a2395440b23";
let returnMap:ReturnMapEntry;
return this.http.get(url).toPromise().then(response => {
let res = response.json();
if (res.status == 1) {
returnMap = { is_ok: true, result: res.locations };
} else {
returnMap = { is_ok: false, msg: '获取地址失败,请您重试!' };
}
return Promise.resolve(returnMap);
}).catch(error => {
console.log(error);
return Promise.reject(error);
});
}
}
直接使用高德地图获取当前位置经纬度(未转换为高德地图坐标)
import { Injectable } from '@angular/core';
declare var AMap;
@Injectable()
export class GeolocationService {
/**
* 高德地图获取当前位置经纬度
*/
goLocation() {
let that = this; let mapObj = new AMap.Map('iCenter');
mapObj.plugin('AMap.Geolocation', function () {
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:无穷大
maximumAge: 0, //定位结果缓存0毫秒,默认:0
convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: true, //显示定位按钮,默认:true
buttonPosition: 'LB', //定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
});
mapObj.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', that.onComplete.bind(that));//返回定位信息
AMap.event.addListener(geolocation, 'error', (data) => {
console.log('定位失败' + data);
}); //返回定位出错信息
});
}
//解析定位结果
onComplete(data) {
console.log(data);
console.log(data.position.toString());
console.log(data.formattedAddress);
var str = ['定位成功'];
str.push('经度:' + data.position.getLng());
str.push('纬度:' + data.position.getLat());
if (data.accuracy) {
str.push('精度:' + data.accuracy + ' 米');
}//如为IP精确定位结果则没有精度信息
str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
// document.getElementById('tip').innerHTML = str.join('<br>');
}
}
根据经纬度获取中文地址
/**
* 根据经纬度获取地址
* @param latitude 纬度
* @param longitude 经度
* @param mapType 地图类型 百度地图 高德地图
*/
showPosition(latitude, longitude, mapType: string = '高德地图'): Promise<ReturnMapEntry> {
let latlon = latitude + ',' + longitude;
let returnMap: ReturnMapEntry;
//百度地图接口
var url = "http://api.map.baidu.com/geocoder/v2/?ak=18246a9bf529aba431bacdc2547dc523&location=" + latlon + "&output=json&pois=0";
if (mapType == '高德地图') {
latlon = longitude + ',' + latitude;
url = "http://restapi.amap.com/v3/geocode/regeo?location=" + latlon + "&key=059b0ae61fe2a851334e9a2395440b23";
}
return this.http.get(url).toPromise().then(response => {
let res = response.json();
if (res.status == 1) {
returnMap = { is_ok: true, result: res.regeocode.formatted_address };
} else {
returnMap = { is_ok: false, msg: '获取地址失败,请您重试!' };
}
return Promise.resolve(returnMap);
}).catch(error => {
console.log(error);
return Promise.reject(error);
});
}
4
5