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>Show on the Map</button></p>
<div id="map"></div>
CSS
#map {
width: 500px;
height: 400px;
}
JavaScript
/* Example will keep adding markers as you enter locations on the input box. It opens the info window of the last marker, but if you click of a different marker, it will show its content. This is because of "closure". Every event handler function of a marker remembers the values
for the objects it had access to, in the moment of its definition.*/
// global variables
var map;
var geocoder;
var infoWindow;
var bounds;
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
// iniatilize global variables before their use
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
bounds = new google.maps.LatLngBounds();
var mapOptions = {
center: { lat: 0, lng: 0},
zoom: 4,
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 showMarkerOnMap(latLng, addressString){
var marker = new google.maps.Marker({
map: map,
position: latLng,
});
// the anonymous function associated to "click" is a closure
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(addressString);
infoWindow.open(map, marker);
});
// trigger click to open window. Without this line, only the marker
// will be shown, but the window is not opened.
google.maps.event.trigger(marker, 'click');
bounds.extend(latLng);
map.fitBounds(bounds);
}
// Function that invokes the "geocode" method and sets the marker on map
function findLocation(aName){
geocoder.geocode( { 'address': aName},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var...