Javascript Geolocation

孤者浪人 提交于 2021-02-08 06:35:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!