计算从用户位置到所选位置的距离,未定义错误lat。

时间:2014-05-07 05:48:03

标签: javascript map geolocation distance navigator

<script type="text/javascript" charset="utf-8">

// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// device APIs are available
//
var location1,location2;
function onDeviceReady() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

// onSuccess Geolocation
//
function onSuccess(position) {
        var cnt,d,lat,lng;

   // var element = document.getElementById('geolocation');
    var element= 'Latitude: '           + position.coords.latitude              + '<br />' +
                  'Longitude: '          + position.coords.longitude             + '<br />' ;

            location1={ "lat":position.coords.latitude,"lon":position.coords.longitude};
            for(var i=0;i<marker_s.length;i++)
            {
                if(marker_s[i].name===document.getElementById("passl").value)
                {
                    cnt++;

                     location2={"lat":marker_s[i].lat,"lon":marker_s[i].lng};
                    // document.write(location2.lat);
                }
            }
    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(location2.lat-location1.lat);  // deg2rad below
    var dLon = deg2rad(location2.lon-location1.lon); 
    var a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(location1.lat)) * Math.cos(deg2rad(location2.lat)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c; // Distance in km
    return d;
    document.write(d);
}

// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

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

}

</script>

0 个答案:

没有答案