0

function showPosition() {
  navigator.geolocation.getCurrentPosition(showMap, error);
}

function showMap(position) {
  // Get location data
  var mylatlong = position.coords.latitude + "," + position.coords.longitude;

  // Set Google map source url
  var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";

  // Create and insert Google map
  document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />

<div id="embedMap">
  <!--Google map will be embedded here-->
</div>

I am new to Javascript and HTML and currently testing out how to get current location and show it in google map after clicking the button. I have tried this but I still cannot get my current location in a map.

app.js

function showPosition() {
             navigator.geolocation.getCurrentPosition(showMap);
         }

         function showMap(position) {
             // Get location data
             var latlong = position.coords.latitude + "," + position.coords.longitude;

             // Set Google map source url
             var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";

             // Create and insert Google map
             document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
         }

index.html

<input type="button" value="Add Map" onclick="showPosition()"/>
 <div id="embedMap">
        <!--Google map will be embedded here-->
    </div>
Elen
  • 2,345
  • 3
  • 24
  • 47
Emma
  • 19
  • 1
  • 6
  • Issue might be that Geolocation has been disabled in this document by Feature Policy. Check [Is there a way to check if geolocation has been DECLINED with Javascript?](https://stackoverflow.com/q/6092400) before using this code. – palaѕн May 16 '20 at 05:48
  • Hello , I have tried checking whether the geolocation got declined but it does not show anything and the map still not working. – Emma May 16 '20 at 06:49
  • I just added the snippet. Thank you! – Emma May 16 '20 at 08:00
  • I have updated the demo. Are you getting any error on button click? – palaѕн May 16 '20 at 08:02
  • Not really. I tried to display the current location in text format and I can see my lat and long clearly. I think the issue is in mapLink. I can also see the "Google Map" alt text tho. Just the map not displaying. – Emma May 16 '20 at 08:05

1 Answers1

1

If you want to get your current position by using Geolocation in JavaScript and HTML, you might like to check this sample code of Google Maps API Javascript. This shows how to create a map that displays the geographic location of a user or device on a Google map, through use of their browser's HTML5 Geolocation feature. The user must consent to location sharing or else an error is shown. Read more about the W3C Geolocation standard. This will then map your coordinates to the map created by Maps JavaScript API.

Here is also a snippet of the sample code I made that geolocates the position after clicking the 'Geolocate' button. Remember to change the string YOUR_API_KEY with your own API key.

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
  <button id="myBtn">Geolocate</button>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 10
        });
        infoWindow = new google.maps.InfoWindow;
document.getElementById("myBtn").addEventListener("click", function(){
        // 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: ' + pos.lat + ',' + pos.lng);
            infoWindow.open(map);
            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.');
        infoWindow.open(map);
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

Hope this helps!

Pagemag
  • 2,779
  • 1
  • 7
  • 17