【问题标题】:Center map to my location中心地图到我的位置
【发布时间】:2016-11-21 19:15:36
【问题描述】:

我有以下代码:

map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: new google.maps.LatLng(53.529773,-113.509387), 
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

如何替换:

center: new google.maps.LatLng(53.529773,-113.509387)

以我当前的位置,以编程方式

【问题讨论】:

  • 看看at this answer。
  • 好吧,也许我解释不正确,我需要用我当前的位置替换:center: new google.maps.LatLng(53.529773,-113.509387),以编程方式
  • 所以,请阅读其他答案。它描述了如何使用地理定位 API 以及如果用户不允许访问它该怎么做。关于用户界面部分有一个很好的讨论。如果您检索到当前坐标,则将它们用于您的 LatLng 对象。如果您不知道如何操作,请阅读有关 JavaScript 的教程。这不是代码编写服务。
  • “您当前的位置”是什么意思?动态的?具体地址?

标签: google-maps


【解决方案1】:

您的代码看起来正确,我怀疑您的问题是您的设备没有启用定位服务,如果是,您可能在第一次运行时没有接受安全提示。

我从 google maps API 参考修改了以下演示 https://developers.google.com/maps/documentation/javascript/

HTML 演示

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JS

function initMap() {

  // Pick a start point, I live in Australia, so just picked the middle of OZ
  var myLatLng = {lat: -25.363, lng: 131.044};

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

  // Mark it on the map, this is the original center
  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });

  // If location services is enabled, the following should center the map on your location.
  if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
            var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            map.setCenter(location);
                });
  }
}

【讨论】:

  • 好吧,也许我解释不正确,我需要用我当前的位置替换:center: new google.maps.LatLng(53.529773,-113.509387),以编程方式
  • 你现在的位置是什么意思?
  • 嗯,我很茫然,这正是你的代码正在做的事情:) var myCurrentLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); map.setCenter(myCurrentLocation);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多