JavaScript Google Maps API - Center on User's Location not loading map

拈花ヽ惹草 提交于 2019-12-13 15:16:30

问题


I've posted before but I wanted to update the question, I tried to delete the other question but I had to flag it do that so I left it alone. I have a key for the Google Map API, but the map will not appear or load. Here is my code:

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:


Try the code below, I tested it locally and over HTTPS, the map will load properly. There were couple issues with your code.

You need to load Google Maps API using async attribute:

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.

Refer to Google's documentation here: Loading the Google Maps Javascript API

Also, make sure the live version is going through secure origin, otherwise you will get these two warning:

[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 initialization needs to be within showLocation() function, position coordinates are currently not passed back to getLocation(), moving your initialization into showLocation() will render the map.

Keep in mind that if your geolocation is not switched on jsFiddle will display a console warning:

ERROR(1): User denied Geolocation

Test it locally or on your server to view the working version.

Revised version with marker based on browser 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>


来源:https://stackoverflow.com/questions/43623427/javascript-google-maps-api-center-on-users-location-not-loading-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!