JavaScript Google Maps API - 用户位置中心未加载地图

时间:2017-04-26 01:19:16

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

我以前发过但是我想更新问题,我试图删除另一个问题,但我不得不标记它这样做,所以我不管它。 我有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;
}

1 个答案:

答案 0 :(得分:1)

尝试以下代码,我在本地测试并通过HTTPS测试,地图将正确加载。你的代码有几个问题。

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

  

async属性允许浏览器呈现您网站的其余部分   加载Maps JavaScript API时。当API准备就绪时,它会   使用callback参数调用指定的函数。

请参阅此处的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了解更多详情。

     

错误(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>