Dil*_*ake 2 native geolocation google-maps-api-3 ionic2 angular
我是离子2原生的初学者.我使用本教程(http://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/)创建了一个简单的位置跟踪应用程序,我想自动更新用户当前用户旅行时的位置.我搜索了教程或任何来源以了解这一点.但我找不到任何东西.如果有人知道有关自动更新用户位置的信息,ioinc 2请告诉我如何做到这一点或给我一个链接.
这是我的代码
export class MapPage {
x: number = 0;
y: number = 0;
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController) {
this.loadMap();
}
loadMap() {
Geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log(position.coords.latitude + " " + position.coords.longitude)
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
console.log(this.map);
}, (err) => {
console.log(err);
});
}
addInfoWindow(marker, content) {
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
showMyLocation() {
Geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(this.x, this.y);
let marker = new google.maps.Marker({
map: this.map,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
position: latLng
});
let content = "<h4>You are here</h4>";
this.addInfoWindow(marker, content);
}, (err) => {
console.log(err);
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是HTML文件
<ion-header>
<ion-navbar>
<ion-title>
Map
</ion-title>
<ion-input type=number style="border: 1px solid black" [(ngModel)]="x"></ion-input>
<ion-input type=number style="border: 1px solid black" [(ngModel)]="y"></ion-input>
<ion-buttons end>
<button ion-button (click)="showMyLocation()"><ion-icon name="add"></ion-icon>Show my location</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map"></div>
</ion-content>
Run Code Online (Sandbox Code Playgroud)
谢谢
只需使用该方法watchPosition而不是getCurrentPosition:
Geolocation.watchPosition().subscribe((position) => {
this.x = position.coords.longitude;
this.y = position.coords.latitude;
let latLng = new google.maps.LatLng(this.x, this.y);
let marker = new google.maps.Marker({
map: this.map,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
position: latLng
});
let content = "<h4>You are here</h4>";
this.addInfoWindow(marker, content);
}, (err) => {
console.log(err);
});
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅https://ionicframework.com/docs/v2/native/geolocation/和https://github.com/apache/cordova-plugin-geolocation#navigatorgeolocationwatchposition.
| 归档时间: |
|
| 查看次数: |
10130 次 |
| 最近记录: |