问题
I'm trying to do some things with geolocation. I want to get back the geolocation latitude and longitude in one variable as array. It doesn't work. I think the first line in the code is the problem. Is it possible to get the value like that (with return)?
startingPoint = navigator.geolocation.getCurrentPosition(onGeoSuccess);
function onGeoSuccess(position) {
start['lat'] = position.coords.latitude;
start['lng'] = position.coords.longitude;
return start;
}
Is there a better solution? I don't want to execute other code in the onGeoSuccess, I want to return the value back.
回答1:
You can try something like this:
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
回答2:
Do Check if Geolocation is supported or not and do code like this
function getLocation()
{
if (navigator.geolocation)//check for support
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
来源:https://stackoverflow.com/questions/16058939/javascript-geolocation