Google Maps Help

Play ground to work with Bill Foss

by iamjpg

HTML

<script src="http://maps.googleapis.com/maps/api/js?v=3&amp;amp;sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&amp;amp;sensor=false"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input name="loc1" placeholder="Enter Location for Map 1">
    </td>
    <td>
      <input name="loc2" placeholder="Enter Location for Map 2">
    </td>
  </tr>
</table>

<div id="map1"></div>

<div id="map2"></div>

CSS

table {
  width: 100%;
}

td {
  width: 50%;
}

#map1 {
  position: absolute;
  top: 40px;
  bottom: 0;
  left: 0;
  width: 50%;
  background: #333;
}

#map2 {
  position: absolute;
  top: 40px;
  bottom: 0;
  right: 0;
  width: 50%;
  background: #ccc;
}

JavaScript

(function() {
	
  // Init the geocoder
	var geocoder = new google.maps.Geocoder();

  // Init Maps
  var map1 = new google.maps.Map(document.getElementById('map1'), {
    center: {
      lat: 47.6062,
      lng: -122.3321
    },
    zoom: 8
  });
  var map2 = new google.maps.Map(document.getElementById('map2'), {
    center: {
      lat: 47.6062,
      lng: -122.3321
    },
    zoom: 8
  });

  // Init click events for geocoding
  $('input').on('keyup', function(e) {
    if (e.which === 13) {
			
      // Exectute on the right map
      var map = (this.name === 'loc1') ? map1 : map2;

      // Geocode and set map to returned viewport.
			geocodeAddress(geocoder, map, this.value);
    }
  });

  // Geocoding Function
  function geocodeAddress(geocoder, resultsMap, locationStr) {
    geocoder.geocode({
      'address': locationStr
    }, function(results, status) {
      if (status === 'OK') {
        resultsMap.fitBounds(results[0].geometry.viewport);
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

})()