javascripthtmlgoogle-mapsgoogle-maps-api-3

How to display a Google Map based on City selected from a Dropdown Menu


I need to display a map based on a place being selected. I need to know how to change the map based on the dropdown menu. Here is what I have so far, but I cannot seem to figure out how to actually change the map using a selection from the dropdown. I am just completely blanking here. Any references or help is greatly appreciated. Here is the code I currently have.

<script>
    function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {  
        center: new google.maps.LatLng(40.685646, -76.195499), zoom: 10 
    };
    var map = new google.maps.Map(mapCanvas, mapOptions);
}

</script>

<div>
    <h2>Please Choose a City</h2>
</div>
<form>
    <fieldset>
        <label>
            Cities
        </label>
        <select id="myCity" name="myCity">
            <option value="None">Select a City</option>
            <option value="PHI">Philadelphia, PA</option>
            <option value="NYC">New York, NY</option>
            <option value="HAR">Hartford, CT</option>
        </select>
    </fieldset>
</form>

Solution

  • Just store the coords by the city key. When the select change, take the value, get the coords and call the method setCenter (docs) with these coords.

    Let me know if something is not clear.

    var map;
    function myMap() {
      var mapCanvas = document.getElementById("map");
      var mapOptions = {  
        center: new google.maps.LatLng(40.685646, -76.195499), 
        zoom: 10 
      };
      map = new google.maps.Map(mapCanvas, mapOptions);
    }
    
    myMap();
    
    var coords = {
      'PHI': '39.953050,-75.163961',
      'NYC': '40.875597,-77.776226',
      'HAR': '41.763633,-72.682662'
    };
    
    function changeMap(city) {
      var c = coords[city].split(',');
      map.setCenter(new google.maps.LatLng(c[0], c[1]));
    }
    #map {
      height: 200px;
    }
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    
    <div>
      <h2>Please Choose a City</h2>
    </div>
    <form>
      <fieldset>
        <label>
          Cities
        </label>
        <select id="myCity" name="myCity" onchange="changeMap(this.value)">
          <option value="None">Select a City</option>
          <option value="PHI">Philadelphia, PA</option>
          <option value="NYC">New York, PA</option>
          <option value="HAR">Hartford, CT</option>
        </select>
      </fieldset>
    </form>
    <div id="map"></div>

    http://output.jsbin.com/suhiveb