使用谷歌地图v3定位用户位置



在这里,我有一个为用户显示地点的代码,但我想根据用户位置显示地点。

如何获取用户的位置并显示在地图上?

我有:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>
function initialize() {
  var markers = [];
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-33.8902, 151.1759),
      new google.maps.LatLng(-33.8474, 151.2631));
  map.fitBounds(defaultBounds); ... ... ... etc.

我尝试添加传感器:true,但它不起作用。

有什么办法可以解决这个问题吗?

您可以尝试使用浏览器的内置地理位置服务(该服务使用 W3C 地理位置标准,因此所有支持 HTML5 的浏览器都应支持)对用户进行地理定位。

您可以在Google Maps JavaScript API v3文档中复制和粘贴代码,如下所示:https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

(顺便说一下,传感器参数只是告诉谷歌你正在使用传感器来确定位置;它本身并不充当传感器)。

包括以下内容以将地图中心定位在当前坐标处:

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);
      var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Here you are.'
      });
      map.setCenter(pos);
    });
  }

最新更新