【问题标题】:JavaScript Google Maps API - Center on User's Location not loading mapJavaScript Google Maps API - 用户位置中心未加载地图
【发布时间】:2017-04-26 01:19:15
【问题描述】:

我之前发布过,但我想更新问题,我试图删除另一个问题,但我不得不标记它,所以我不理会它。 我有 Google Map API 的密钥,但地图不会显示或加载。 这是我的代码:

Index.html

<script src = "loc.js"></script>
<input type ="button" value="Get Location" onclick="getLocation();">
<div id="spot"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDEiqN2L1odkK645Il8bBVCDqatth6aZyU&callback=getLocation"></script>
<div id="map" style="width:100%;height:400px;"></div>

loc.js

function getLocation() {
    var userSpot = document.getElementById("spot");
    var map = document.getElementById("map");
    //Using navigator, retrieves the users current location (works better with mobile phones)
    if (navigator.geolocation) { //If the user says no (this prompts the user if they want their location known)
                                //then it'll go ahead and retrieve their location, if not prompts error message.
        navigator.geolocation.getCurrentPosition(showLocation);

        var currPosLat = position.coords.latitude; 
        var currPosLng = position.coords.longitude;

        var mapOptions = { 
        center: new google.maps.LatLng(currPosLat, currPosLng),
        zoom:12, 
        }; 

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    } else { 
        userSpot.innerHTML = "Geolocation is not supported by this browser type.";
    }
}

function showLocation(position) {
    var userSpot = document.getElementById("spot");
    //Retrieves latitude and longitude using this second function called in the first
    userSpot.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}

【问题讨论】:

  • 强调一下,主要问题在于 div id = map 应该在哪里,以及 loc.js 中的 getLocation 方法。这就是我的问题的根源。

标签: javascript google-maps google-maps-api-3 geolocation


【解决方案1】:

试试下面的代码,我在本地和通过 HTTPS 进行了测试,地图将正确加载。您的代码存在几个问题。

您需要使用async 属性加载Google Maps API:

异步属性让浏览器呈现您网站的其余部分 在加载 Maps JavaScript API 时。当 API 准备就绪时,它将 调用使用回调参数指定的函数。

请参阅此处的 Google 文档:Loading the Google Maps Javascript API

另外,请确保实时版本通过安全来源,否则您将收到以下两个警告:

[弃用] getCurrentPosition() 和 watchPosition() 不再起作用 关于不安全的起源。要使用此功能,您应该考虑 将您的应用程序切换到安全源,例如 HTTPS。看 https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins了解更多详情。

ERROR(1): 只允许安全来源(请参阅: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features)。

地图初始化需要在showLocation()函数内,位置坐标目前没有传回getLocation(),将你的初始化移动到showLocation()会渲染地图。

请记住,如果您的地理位置未打开,jsFiddle 将显示控制台警告:

错误(1):用户拒绝地理位置

在本地或在您的服务器上对其进行测试以查看工作版本。

带有基于浏览器地理位置标记的修订版本:

function getLocation() {
	var userSpot = document.getElementById("spot");
	var map = document.getElementById("map");
	//Using navigator, retrieves the users current location (works better with mobile phones)
    if (navigator.geolocation) { //If the user says no (this prompts the user if they want their location known)
								//then it'll go ahead and retrieve their location, if not prompts error message.
        navigator.geolocation.getCurrentPosition(showLocation, error);
        
    } else { 
        userSpot.innerHTML = "Geolocation is not supported by this browser type.";
    }
}

function showLocation(position) {
	var userSpot = document.getElementById("spot");
	//Retrieves latitude and longitude using this second function called in the first
    userSpot.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
    
    var currPosLat = position.coords.latitude; 
    var currPosLng = position.coords.longitude;
    var centerPosition = new google.maps.LatLng(currPosLat, currPosLng);
    var bounds = new google.maps.LatLngBounds();
    
    var mapOptions = { 
      center: centerPosition,
      zoom:12
    }; 

    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    bounds.extend(centerPosition);
    marker = new google.maps.Marker({
        position: centerPosition,
        map: map,
        //icon: 'map.png',
        title: 'Some Random Location'
    });
    
};

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};
<script src = "loc.js"></script>
<input type ="button" value="Get Location" onclick="getLocation();">
<div id="spot"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDEiqN2L1odkK645Il8bBVCDqatth6aZyU&callback=getLocation"></script>
<div id="map" style="width:100%;height:400px;"></div>

【讨论】:

  • 非常感谢,这完全使它工作。我也看到了它是如何工作的,不确定什么是异步,但它和其他代码一样成功了。我记得在我的教科书中看到了边界和标记变量,但没想到要包括它。另外,一个附带问题,函数错误中使用的那些“$”符号是什么?如:('ERROR(${err.code}): ${err.message}');它几乎看起来像另一种语言,括号内有大括号,中间有一个冒号。
  • 太棒了。根本不是一种不同的语言,仍然是 javascript。 err.code返回错误码(如果有),err.message返回错误码相关信息。
猜你喜欢
  • 2016-09-03
  • 2013-06-27
  • 2017-04-10
  • 2013-03-19
  • 2014-01-10
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多