【问题标题】:I can't center my map on geolocation我的地图无法以地理位置为中心
【发布时间】:2017-08-28 16:16:22
【问题描述】:

我在将我的地图设置为居中并放大用户的地理位置时遇到了一些麻烦。我试图将 (lat, lng) 传递给“中心:”参数,但我得到一个空白屏幕。 这是我的代码。

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: mylat, lng: mylng},
      zoom: 14
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          mylat: position.coords.latitude,
          mylng: position.coords.longitude
        };

        map.setCenter(pos);
        zoom: 13

      },

【问题讨论】:

  • 请提供一个minimal reproducible example 来证明该问题。发布的代码包含语法错误:Uncaught SyntaxError: Unexpected token var
  • 是的,先生,删除了所有不相关的代码。当我尝试将我的 lat long 变量传递给中心函数时出现我的问题
  • 如果我使用常规坐标,页面加载正常
  • 我希望发布的代码会出现另一个 javascript 错误,因为未定义 mylatmylng。请提供一个(工作中的)minimal reproducible example 来证明您的问题。

标签: javascript google-maps google-maps-api-2


【解决方案1】:

尝试使用 LatLng 对象而不是 literalLatLng

 map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));

然而 literLatLng 需要 lat, lng (不是 myLat, myLng)

 var pos = {
     lat: position.coords.latitude,
     lng: position.coords.longitude
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2019-04-06
    • 1970-01-01
    • 2015-05-10
    相关资源
    最近更新 更多