在Google地图中获取当前位置并将其传递给JavaScript中的变量 [英] Getting current location in google map and pass it to a variable in javascript

查看:88
本文介绍了在Google地图中获取当前位置并将其传递给JavaScript中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要显示从当前位置到已知位置的Google地图中的方向。我的代码如下所示:

I want to display a direction in google map from current location to a known location. my code is shown below:

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

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var bne = new google.maps.LatLng(-27.572832, 153.065247);
  var mapOptions = {
    zoom:7,
    center: bne
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}


function calcRoute() {
  navigator.geolocation.getCurrentPosition(
    function (pos) {
      var start = new google.maps.LatLng(pos.coords.latitiude,
                                         pos.coords.longitude);

      var end = 'sunnybank,brisbane';
      var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    }, 
    function (err) {
      alert('ERROR(' + err.code + '): ' + err.message);
    });
  }

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

    </script>

似乎navigator.geolocation.getCurrentPosition()不适合我,还有其他方法检索当前位置并将其传递给启动变量?

It seems that navigator.geolocation.getCurrentPosition() doesn't work for me, is there other ways to retrieve current location and pass it to start variable?

推荐答案

通过 documentation ,getCurrentPosition函数会传递一个定位对象到它的回调函数(它是异步的,所以不能返回任何东西),它不是google.maps.LatLng对象但包含创建一个所需的信息)。

Per the documentation, the getCurrentPosition function passes a Position object to its callback function (it is asynchronous so can't return anything), which is not a google.maps.LatLng object (but contains the information required to create one).

function calcRoute() {
  navigator.geolocation.getCurrentPosition(function(pos) {
    var start = new google.maps.LatLng(pos.coords.latitiude,
                                       pos.coords.longitude);

    var end = 'sunnybank,brisbane';
    var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      } else alert("Directions request failed: "+status);
    });
  }, function(err) {
    alert('ERROR(' + err.code + '): ' + err.message);
  });
}

概念证明小提琴

这篇关于在Google地图中获取当前位置并将其传递给JavaScript中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆