我已经在angular中实现了mapbox的概念,我还在地图中添加了确定当前位置的标记,目前iam通过json文件给出了硬编码的当前位置(以及经纬度),现在我实际上想确定当前位置,即我想通过给出经纬度作为输入来实现反向地理编码的概念。
目前我正在做的代码是这样的。
import { Component, OnDestroy, AfterViewInit, OnInit } from '@angular/core';
import { NavigationControl, Map } from 'mapbox-gl';
import {ActivatedRoute, Router,ParamMap } from '@angular/router';
import { environment } from 'src/environments/environment';
import * as mapbox from 'mapbox-gl';
(mapbox as any).accessToken = environment.mapbox.accessToken
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
})
export class DashboardComponent implements OnInit,AfterViewInit {
latlng:any;
constructor(private route:ActivatedRoute,
private router:Router)
{
this.loadMap();
}
ngOnInit() {
}
ngAfterViewInit(){
}
loadMap(){
var latitude=this.latitude;
var longitude=this.longitude;
this.latlng=[longitude,latitude]
var map1=new Map(
{
container:'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: { lng: longitude, lat: latitude },
zoom: 9,
pitch: 20,
attributionControl: false
});
map1.addControl(
new NavigationControl({
showZoom: true,
showCompass: true
}),
'top-right'
);
var el = document.createElement('div');
el.style.backgroundImage = "url('../../assets/images/truck.png')";
el.style.backgroundSize='cover';
el.style.width = '50px';
el.style.height = '50px';
el.style.marginTop='-35px'
el.style.cursor='pointer';
new mapbox.Marker(el)
.setLngLat(this.latlng)
.setPopup(new mapbox.Popup({offset:25})
.setHTML('<p>'+this.orderItem.current_location+'</p>'))
.addTo(map1);
}
}
你可以使用Geolocation控件来获取当前位置。
navigator.geolocation.getCurrentPosition(success, error, options);
你必须用选项来调用它,比如这些。
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
你必须实现错误和成功的回调。
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
一旦成功,你就可以使用返回的坐标。例如,您可以在反向地理编码请求中使用它们。
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
也请看这个文档。
https:/developer.mozilla.orgen-USdocsWebAPIGeolocationgetCurrentPosition。
如果有什么不清楚的地方请告诉我!