Address to Lat Lng

by Ben Clayton

HTML

<div id="floating-panel">
  <input id="address" type="textbox" value="Tesco TN38 9RB">
  <input id="submit" type="button" value="Geocode">
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

CSS

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

JavaScript

/* 
* https://developers.google.com/maps/documentation/geocoding/intro
*/
var map;
function initMap() {
   map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: {
               "lat" : 50.8774555,
               "lng" : 0.5364637999999999
            }

  });
  var geocoder = new google.maps.Geocoder();

  document.getElementById('submit').addEventListener('click', function() {
    geocodeAddress(geocoder, map);
  });
}

function geocodeAddress(geocoder, resultsMap) {
  var address = document.getElementById('address').value;
  // https://maps.googleapis.com/maps/api/geocode/json?&address=tesco%20hastings
  geocoder.geocode({'address': address}, function(results, status) {
    if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}