【问题标题】:How to pull user's current location and display on google map api? [duplicate]如何拉取用户的当前位置并显示在谷歌地图 api 上? [复制]
【发布时间】:2018-01-22 17:57:46
【问题描述】:

所以我要完成两件事 1) 拉取用户当前位置 2)然后在谷歌地图上显示它

从我的研究中,我看到我可以使用以下内容来获取用户的当前位置

navigator.geolocation.getCurrentPosition(success);
function success(pos) {
  var crd = pos.coords;
  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
};

和以下启动谷歌地图

function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
    });
    var marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }

所以我遇到的问题是如何同时完成两者? 我试图将第二个函数放在第一个函数中,但这不起作用...... 提前感谢大家的帮助!

【问题讨论】:

标签: javascript google-maps


【解决方案1】:

initMap 需要知道位置是什么。目前,您在 initMap 中将位置设置为“uluru”;相反,尝试将坐标传递给函数,然后从该对象中拉出坐标(您可以重用该对象,但您必须考虑到字段被称为 longitude/latitude 的事实第一种情况,lng/lat 在第二种情况下)。像这样的:

navigator.geolocation.getCurrentPosition(success);
function success(pos) {
  var crd = pos.coords;
  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
  initMap(crd);
};

function initMap(coordinates) {
    var location = {'lng': coordinates.longitude, 'lat': coordinates.latitude};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: location
    });
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
}

【讨论】:

  • 谢谢!我现在开始工作了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2015-08-14
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
相关资源
最近更新 更多