JSFiddle - React, Tailwind, and code Playground

by brightonmike

HTML

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<input type="text" id="address1"/><input type="text" id="address2"/><input type="submit" id="init_map"/>
<div id="map_canvas">Enter locations and click Submit</div>

CSS

#map_canvas {
    background:#ccc;
    height:400px;
    width:100%;
}

JavaScript

var map;

function initialize() {
    var myOptions = {
        zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
        // List of locations, obviously this would be replaced by your input values
        locations = [document.getElementById('address1').value, document.getElementById('address2').value];

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    addMarkers(locations);
}

// addMarkers function, takes an array of plain english addresses, geocodes 
// them and then adds as markers with the original address the title


function addMarkers(locations) {
    var bounds = new google.maps.LatLngBounds(),
        geocoder = new google.maps.Geocoder();

    // Loop through locations array
    for (var i = 0; i < locations.length; i++) {
        // Use geocode service to find latlng
        geocoder.geocode({
            'address': locations[i]
        }, function(results, status) {

            if (status == google.maps.GeocoderStatus.OK) {

                // Add as marker
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: locations[i]
                });

                // Add latlng to bounds
                bounds.extend(results[0].geometry.location);
                // Center map according to bounds
                map.fitBounds(bounds);

            } else {
                console.log("Could not geocode [" + locations[i] + "] Message: " + status);
            }

        })

    }
}

document.getElementById("init_map").onclick = function() {
    initialize();
    return false;
}