I created the following function in a service, to get the coordinates of the current location and store them in 2 variables:
getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.currLat = position.coords.latitude;
this.currLng = position.coords.longitude;
});
}
else {
alert("Geolocation is not supported by this browser.");
}
}
how can I return the coordinates through this function in order to use them in a component?
You could return a promise.
locationService.ts
getPosition(): Promise<any>
{
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resp => {
resolve({lng: resp.coords.longitude, lat: resp.coords.latitude});
},
err => {
reject(err);
});
});
}
component.ts
this.locationService.getPosition().then(pos=>
{
console.log(`Positon: ${pos.lng} ${pos.lat}`);
});
以防万一,如果您想不断请求该职位,请使用
navigator.geolocation.watchPosition(res => ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.