Search code examples
javascriptgoogle-mapsgoogle-maps-api-3kmlkmz

Apply Zoom In Zoom out feature by clicking dropdown list any value


current screen is here. i m showing some locations in the map.locations are basically markers ,you can see markers in this picture.what i want to do is,,,current screen is here. i m showing some locations in the map.locations are basically markers ,you can see markers in this picture.what i want to do is,,,

when i change the dropdownlist value i want to zoom in the chart where i can easily see one of the marker position after clicking some another dropdownlist value like when i click on PG & E the google map will zoom in to the specific marker. i will share my code with you. most importantly i am using kml file to load the map on the screen. when i change the dropdownlist value i want to zoom in the chart where i can easily see one of the marker position after clicking some another dropdownlist value like when i click on PG & E the google map will zoom in to the specific marker. i will share my code with you.

<script>
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.HYBRID
        //   center: {lat: 41.876, lng: -87.624}
    });

    var ctaLayer = new google.maps.KmlLayer({url:'https://sites.google.com/site/kmzmap1/plm/868l_little%20falls-st%20stephens%202%20.kmz?attredirects=0&d=1',
        map: map
    });
}

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">

and my html code is .....

<div id="map" style="width:100%;height:478px;"></div>

Solution

  • You will need to use JQuery to achieve this. I will work through an example.

    Define a Select box:

    <select>
     <option >Choose...</option>
      <option value="in">zoom in</option>
      <option value="out">zoom out</option>
    </select>
    

    We then need to ensure that the map is globally defined so we can access anywyere within the <script> aspect of the page

    var map;

    then assign your map to that variable map = new google...

    We then use jquery to listen to the select box and perform some sort of action:

    $('select').on('change', function() {
        var optionSelected = $("option:selected", this);
        var valueSelected = this.value;
        if(valueSelected == 'in'){
          map.setZoom(17);
        } 
        if(valueSelected == 'out'){
        map.setZoom(4);
        map.panTo(new google.maps.LatLng(33.818038, -117.928492));
        }
    })
    
    • optionSelected gets the value of this select box (having multiple you probably be best basing this on ID rather than generic select).
    • valueSelected is the value of this selected item (in my example in or out).
    • we then call what to do; if in we increase the zoom in, if out we zoom out and pan to a coordinate (this could be a marker).

    JSFiddle : http://jsfiddle.net/4mtyu/2741/