JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="origin"></div>
<div id="destination"></div>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
CSS
html, body, #map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
JavaScript
var geocoder;
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocodeLocations(
new google.maps.LatLng(40.7127837, -74.0059413),
new google.maps.LatLng(40.735657, -74.1723667));
}
google.maps.event.addDomListener(window, "load", initialize);
function geocodeLocations(origin, destination) {
var geocoder = new google.maps.Geocoder();
var geocoder2 = new google.maps.Geocoder();
var geocodedOrigin;
var geocodedDestination;
var geocodedLocations;
var bounds = new google.maps.LatLngBounds();
geocoder.geocode({
'location': origin
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
geocodedOrigin = results[1].formatted_address;
var marker = new google.maps.Marker({
position: results[1].geometry.location,
map: map
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
document.getElementById('origin').innerHTML = "origin=" + geocodedOrigin;
} else {
geocodedOrigin = 'No results found';
}
} else {
geocodedOrigin = 'Geocoder failed due to: ' + status;
}
});
geocoder2.geocode({
'location': destination
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
geocodedDestination = results[1].formatted_address;
var marker = new google.maps.Marker({
position: results[1].geometry.location,
map: map
});
bounds.extend(marker.getPosition());
...