Google Maps JavaScript API - User Location Center Not Loading Map

I wrote earlier, but I wanted to update the question, I tried to delete another question, but I had to point out that this is the case, so I left it alone. I have a key for the google maps API, but the map won't display 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;
}

      

+3


source to share


1 answer


Try below code, I checked it locally and over HTTPS, the map will load properly. There were problems with the code.

You need to load the Google Maps API using the attribute async

:

The asynchronous attribute allows the browser to display the rest of your site while the Maps JavaScript API is being loaded. When the API is ready, it will call the function specified using the callback parameter.

Refer to Google documentation here: Downloading the Google Maps Javascript API

Also, make sure the live version goes through a safe start, otherwise you will receive the following two warnings:

[Fatigue] 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 origin allowed (see https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features ).

The map initialization must be within the function showLocation()

, the location coordinates are not currently being passed back to getLocation()

, moving your initialization to showLocation()

will render the map.



Be aware that if your geolocation is not enabled, jsFiddle will display a console warning:

ERROR (1): User denied geolocation

Check it out locally or on your server to see a working version.

Revised version with a 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>
      

Run codeHide result


+1


source







All Articles