Вопрос

I want to access(or print) d from return of function getDistanceFromLatLonInKm just by calling get.Location .I guess I may use callbacks but it dosent't work(and/or I'm a n00b).Is it possible to do this in this case? For example :document.write(getLocation(45.123,12.123)) //would print d somehow .

Thank you in advance.

getLocation(45.123,12.123);

function getLocation(a,b) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(p){ajmo(p,a,b);});
  }
}

function ajmo(position,a,b) {
  lat = position.coords.latitude;
  lng = position.coords.longitude;
  getDistanceFromLatLonInKm(a,b,lat, lng);
}


function getDistanceFromLatLonInKm(lat_origin, lon_origin, lat_pos, lon_pos) {
  var R = 6371;
  var dLat = deg2rad(lat_pos - lat_origin);
  var dLon = deg2rad(lon_pos - lon_origin);
  var a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat_origin)) * Math.cos(deg2rad(lat_pos)) * 
    Math.sin(dLon / 2) * Math.sin(dLon / 2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}     
Это было полезно?

Решение

Assuming you have an HTML element with id = "distance", you probably need this:

function getLocation(a, b, element) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      lat = position.coords.latitude;
      lng = position.coords.longitude;
      var d = getDistanceFromLatLonInKm(a,b,lat, lng);
      document.getElementById(element).innerHTML = d;
    });
  }
}


function getDistanceFromLatLonInKm(lat_origin, lon_origin, lat_pos, lon_pos) {
  var R = 6371;
  var dLat = deg2rad(lat_pos - lat_origin);
  var dLon = deg2rad(lon_pos - lon_origin);
  var a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat_origin)) * Math.cos(deg2rad(lat_pos)) * 
    Math.sin(dLon / 2) * Math.sin(dLon / 2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}  


getLocation(45.123, 12.123, 'distance');
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top