JavaScript Google Maps API - 以用户位置为中心不加载 map

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

我之前发布过,但我想更新这个问题,我试图删除另一个问题,但我不得不标记它这样做,所以我把它留了下来。 我有 Google Map API 的 key ,但 map 不会显示或加载。 这是我的代码:

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;
}

最佳答案

尝试下面的代码,我在本地和通过 HTTPS 测试了它, map 将正确加载。您的代码有几个问题。

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

The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter.

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

此外,请确保在线版本正在通过安全来源,否则您将收到以下两个警告:

[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

ERROR(1): Only secure origins are allowed (see: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features).

map 初始化需要在 showLocation() 函数中进行,位置坐标目前不会传回 getLocation(),将您的初始化移动到 showLocation() 将渲染 map 。

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

ERROR(1): User denied Geolocation

在本地或您的服务器上测试它以查看工作版本。

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

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>

关于JavaScript Google Maps API - 以用户位置为中心不加载 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43623427/

相关文章:

javascript - 未捕获的无效值错误 : unknown property origin

javascript - 将 mouseevent 传递给 googlemaps 事件监听器

javascript - 谷歌地图 API : How to Set Scroll Zoom to Anchor in on One Marker

javascript - 为异步函数创建回调

javascript - jQuery - Ajax 不返回 json 响应

javascript - 优化 jQuery 剧透按钮

jquery - Yii 和 EGMap 扩展(Google map )在复选框更改时刷新 map

javascript - 拖动浏览器导致背景图像与下一节重叠

javascript - 将数组从 NodeJS 服务器传递到客户端?

javascript - 在谷歌地图中拖放标记