Show User Location On Google Maps Using JavaScript

Google API Javascript

1. Create an API key from Google Cloud Platform that you need to access Google Maps API.

2. Replace your API key inside Google Maps JavaScript script tag at the bottom of the HTML code below.

3. Define div element with an id of map.

<html>
<head>
    <style>
        #map {
            height: 100%;
        }
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>

</head>

<body>
    <div id="map"></div>
</body>

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

</html>

4. Get user’s location in the form of Latitude and Longitude using getCurrentPoistion() method which a part of HTML5 Geolocation JavaScript API.

app.js

navigator.geolocation.getCurrentPosition(
    function (position) {
        initMap(position.coords.latitude, position.coords.longitude)
    },
    function errorCallback(error) {
        console.log(error)
    }
);

5. Inside the success callback function, invoke initMap() with Latitude and Longitude values as arguments 

function initMap(lat, lng) {
    var myLatLng = {
        lat,
        lng
    };

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 15,
        center: myLatLng
    });

    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: 'Hello World!'
    });
}

 

Comments Count: 0 0