JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyANh0YzZG-vsBwun96VJTXO6OGqnjIpzCE"></script>
<p>Enter a location name: <input><button>Find!</button></p>
<div id="map"></div>
CSS
#map {
width: 500px;
height: 400px;
}
JavaScript
var map;
var geocoder; // global variable
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 42.066667, lng: -71.293056},
zoom: 6,
mapTypeId: 'roadmap',
scrollwheel: false
};
map = new google.maps.Map(document.querySelector('#map'),
mapOptions);
}
// grab the search phrase from the input box
var button = document.querySelector("button");
button.onclick = function(){
var locName = document.querySelector("input").value;
findLocation(locName);
}
// Function that invokes the "geocode" method and sets
function findLocation(aName){
geocoder.geocode( { 'address': aName},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("found location: " + aName,
results[0].geometry.location);
console.log("Result: ", results[0].geometry.location);
map.setCenter(results[0].geometry.location);
}
});
}