HTML5 Game - Show your location on google map with error handler

Description

Show your location on google map with error handler

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Geolocation Map</title>

<style>
#mapSurface {//from  ww w .j a  va 2 s  . c o  m
  width: 600px;
  height: 400px;
  border: solid 1px black;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

<script>

let results;
let map;


window.onload = function() {
  results = document.getElementById("results");
  let mapOptions = {
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mapSurface"), mapOptions);


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      geolocationSuccess, geolocationFailure
    );

    results.innerHTML = "The search has begun.";
  } else {
    results.innerHTML = "This browser doesn't support geolocation.";
  }
}

function geolocationSuccess(position) {

      let location = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(location);

let infowindow = new google.maps.InfoWindow();

      infowindow.setContent("You are here, or somewhere thereabouts.");
      infowindow.setPosition(location);
      infowindow.open(map);

 results.innerHTML = "Now you're on the map.";
}

function geolocationFailure(positionError) {
  if (positionError.code == 1) {
    results.innerHTML = 
     "You decided not to share, but that's OK. We won't ask again.";
  }
  else if (positionError.code == 2) {
    results.innerHTML =
     "The network is down or the positioning service can't be reached.";
  }
  else if (positionError.code == 3) {
    results.innerHTML =
     "The attempt timed out before it could get the location data.";
  }
  else {
    results.innerHTML =
     "This the mystery error. Something else happened, but we don't know what.";
  }
}

</script>
</head>

<body>
  <p id="results">Where do you live?</p>
  <div id="mapSurface"></div>

</body>
</html>

Related Topic