【问题标题】:Geolocation using current location as variable使用当前位置作为变量的地理位置
【发布时间】:2014-01-20 00:21:24
【问题描述】:

我已修改此代码以尝试使其适用于我的情况。我正在尝试做的是找到访问者的当前位置,并在加载时将路线映射到某个位置。

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">  
</script>

<script>
  var directionsDisplay;
  var directionsService = new google.maps.DirectionsService();

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
        zoom: 7,
        center: new google.maps.LatLng(38.3094610,-85.5791560)
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
    var control = document.getElementById('control');
    control.style.display = 'block';
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
  }

  function calcRoute() {
    var start = 'current location';
    var end = ('38.3094610,-85.5791560');
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING
     };

    directionsService.route(request, function(result, status) {
       if (status == google.maps.DirectionsStatus.OK) {
           directionsDisplay.setDirections(result);
       }
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);

</script>

我需要将当前位置存储在一个变量中,这样我就可以在 calcRoute 函数作为开始。

【问题讨论】:

  • 欢迎来到 Stack Overflow。在提出问题时,您应该真正尝试证明您已经做出了一些努力来解决问题并进行了彻底的研究。您不能只是转储大量代码并期望人们为您修复它。有关提出好问题的指南,请参阅此处stackoverflow.com/questions/how-to-ask
  • 不想在这里粗鲁,但我在第一行就说了这么多。“我已经调整了这段代码,试图让它适应我的情况” 改编的意思是我已经改变/改变了/试图让它工作。另外,我已经尝试过对此进行研究,您认为我是如何来到这个网站的?
  • 新用户提出的所有问题都经过审核流程,以确保它们符合上述指南,并确保您了解它们的重要性。在这种情况下,我觉得您的问题可以通过那篇文章中的一些建议得到改善。如果您选择这样做当然取决于您。

标签: javascript html variables geolocation currentlocation


【解决方案1】:

首先检测浏览器是否支持地理跟踪:

if (!window.navigator||
    !window.navigator.geolocation||
    !window.navigator.geolocation.watchPosition) return;

然后构建位置处理程序:

function geo_success(pos){
  var lat=pos.coords.latitude;
  var lng=pos.coords.longitude;

  //do your mapping magic here
}

function geo_error(pos){
  // do nothing
}

现在注册跟踪器:

navigator.geolocation.watchPosition(
    geo_success, geo_error, 
    {enableHighAccuracy:true, maximumAge:10000, timeout:10000});

【讨论】:

    【解决方案2】:

    您是在问如何从浏览器获取地理位置?如果是这样,请尝试this article

    TL;DR

    navigator.geolocation.getCurrentPosition(callback);
    

    其中callback 是在确定用户位置后调用的 javascript 函数。

    【讨论】:

    • 我没有在代码中看到它是从哪里获得的,我已经搜索了有关如何获得它们的示例,但我很难实现它们。我所做的每一项更改都会导致部分页面加载。这似乎是最简单的,但我无法实现它 lol var lat=pos.coords.latitude; var lng=pos.coords.longitude; @Mike
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2013-10-27
    • 2018-10-17
    • 2011-09-23
    • 2023-03-25
    相关资源
    最近更新 更多