【问题标题】:Print distance from current location to another location javascript打印从当前位置到另一个位置的距离javascript
【发布时间】:2016-01-12 02:12:14
【问题描述】:

我得到了下面的代码来计算从当前位置到另一个位置的距离,谁能帮我把这段代码合并到 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()
  }
}

【问题讨论】:

    标签: javascript geolocation


    【解决方案1】:

    您的代码似乎来自此博客: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 调用您的代码定义的方法

    代码示例:

    1. jQuery 包括:
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    
    1. HTML 容器:
    <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. 地理位置调用:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2021-07-06
      • 2016-06-07
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多