打印从当前位置到另一个位置的距离javascript

时间:2016-01-11 17:07:33

标签: javascript geolocation

我得到以下代码来计算从当前位置到另一个位置的距离,任何人都可以帮我如何在HTML文件中合并此代码并打印该HTML页面上的距离?

我对JavaScript的了解不多。请帮忙。

var Geolocation = {
  rad: function(x) { return x * Math.PI / 180 },

  // Distance in kilometers between two points using the Haversine algo.
  haversine: function(p1, p2) {
    var R = 6371
    var dLat  = this.rad(p2.latitude - p1.latitude)
    var dLong = this.rad(p2.longitude - p1.longitude)

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(this.rad(p1.latitude)) * Math.cos(this.rad(p2.latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2)
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    var d = R * c

    return Math.round(d)
  },

  // Distance between me and the passed position.
  distance_from: function(position) {
    Geolocation.display_location()
    var distance = Geolocation.haversine(position.coords, current_location)

    // Sugar: If distance is less than 1km, don't bump into me.
    if ( distance && distance > 0 ) $("#distance").text(distance + " km")
    else $("#user_distance").html("<strong>You're close!</strong> Watch my toes!")
  },

  // Hide spinner and show location.
  display_location: function() {
    $("#user_distance").show()
    $("#geolocating").hide()
  }
}

1 个答案:

答案 0 :(得分:0)

您的代码看起来来自此博客:http://breakthebit.org/post/10512237123/using-html5-geolocation-api-to-get-the-distance-of

有一个演示:http://miha.rebernik.info/

最终只是:

  1. Include jQuery页面中的JavaScript库。
  2. 添加相应的HTML容器(ID user_distancedistance以及可能geolocating)。
  3. 使用geolocation API调用您的代码所定义的方法
  4. 代码示例:

    1. jQuery包括:
    2. <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
      
      1. HTML容器:
      2. <p id="geolocating">Please share your location…</p>
        
        <p id="user_distance">
            Distance from position (latitude: YY, longitude: XX) to you:
            <span id="distance"></span>
        </p>
        
        1. 地理定位电话:
        2. var current_location = {
              latitude: 48.86,
              longitude: 2.35
          };
          
          if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(Geolocation.distance_from, Geolocation.display_location);
              navigator.geolocation.watchPosition(Geolocation.distance_from);
          } else {
              Geolocation.display_location();
          }
          

          演示:http://plnkr.co/edit/zk8Ph9mNIaPsyFpWd8u4?p=preview