Search code examples
javascriptphpgoogle-maps-api-3ngrok

Google maps javascript API "geolocation service failed" in server but works on local


So I set up a ngrok temporary server to show my employer how her website is looking but then noticed that google map's Javascript API fails while on ngrok, while on my localhost it's working, is this some quirk with ngrok or will it happen when we start hosting it on a real server? I have the geolocation on /scripts/js/geolocation.js and the page that is calling it is on /orders.php

geolocation.js:

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 6
    });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

orders.php:

<div id="map">
    <script>initMap()</script>
</div>


<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=REDACTED&callback=initMap">
</script>

Localhost: Local:

Ngrok: Ngrok


Solution

  • For future reference of someone that might need help with this aswell:

    Question solved with the help of @AwPa, @RamRaider, @HaythamROUIS. So the problem was that the server was in http instead of https, the only thing you need to do is (if you are using ngrok) place https:// in the beginning of the url since ngrok hosts both http and https at the same time, or change your webserver's configuration to use HTTPS.

    https link on ngrok: ngrok

    Important Note: Like @RamRaider said, use , do this with everything you fetch using URL's, it's better not to hardcode the protocol that will be used, doing it this way will use the protocol that is currently being used on the website, in this case https.