[Solved] Google API: User current location using JavaScript not displaying

Last Reply 7 months ago By dharmendr

Posted 7 months ago

hello,

 

i am using this snippet to trace the current location of user but it is not working please check and advice thanks

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (p) {
            var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': LatLng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        document.getElementById("lblAddress").innerHTML = "Your location: <b>" + results[1].formatted_address + "</b>";
                    }
                }
            });
        });
    } else {
        alert('Geo Location feature is not supported in this browser.');
    }
</script>
<asp:Label ID="lblAddress" runat="server" />
Output

Your location: KanyaPada Road, Kanyapada, Gokuldham Colony, Goregaon East, Mumbai, Maharashtra 400063, India

 

Posted 7 months ago
nauna says:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

You are not passing the API Key. You need to add the API Key in the url.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&key=AIzaSyBE1J5Pe_GZXBR_x9TXOv6TU5vtCSmEPW4"></script>

HTML

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&key=AIzaSyBE1J5Pe_GZXBR_x9TXOv6TU5vtCSmEPW4"></script>
<script type="text/javascript">
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (p) {
            var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': LatLng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        document.getElementById("lblAddress").innerHTML = "Your location: <b>" + results[1].formatted_address + "</b>";
                    }
                }
            });
        });
    } else {
        alert('Geo Location feature is not supported in this browser.');
    }
</script>
<span id="lblAddress"></span>

Demo