Search code examples
javascriptgoogle-maps-api-3onclicklistener

click function for multiple buttons loading marker in one google map javascript


What I want to achieve is one map, with several (in this case three) buttons, when you click a button, the map loads a marker with that buttons location. So you could "jump" from one location to the next.

I get it working with three separate functions and eventlisteners but I would think there is a way to concatenate it all down to just one function? The working solution is commented out in the code example below...

<div id="floating-panel">
<input id="address-1" class="address" value="Paris" type="button">
<input id="address-2" class="address" value="London"  type="button">
<input id="address-3" class="address"  value="New York" type="button">

var address = null;

function initMap() {    

        var geocoder = new google.maps.Geocoder();

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: @MapZoom,
            center: { lat: @MapCenterLat, lng: @MapCenterLng}
    });

    document.getElementByClassName('address').addEventListener('click', function () {
            address = this.value();
            geocodeAddress(geocoder, map);
    });

        //document.getElementById('address-1').addEventListener('click', function () {
        //    geocodeAddress1(geocoder, map);
        //});
        //document.getElementById('address-2').addEventListener('click', function () {
        //    geocodeAddress2(geocoder, map);
        //});
        //document.getElementById('address-2').addEventListener('click', function () {
        //    geocodeAddress3(geocoder, map);
        //});

 }

function geocodeAddress(geocoder, resultsMap) {

    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: resultsMap,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

//function geocodeAddress1(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}
//function geocodeAddress2(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}
//function geocodeAddress3(geocoder, resultsMap) {

//    geocoder.geocode({ 'address': address }, function (results, status) {
//        if (status === 'OK') {
//            resultsMap.setCenter(results[0].geometry.location);
//            var marker = new google.maps.Marker({
//                map: resultsMap,
//                position: results[0].geometry.location
//            });
//        } else {
//            alert('Geocode was not successful for the following reason: ' + status);
//        }
//    });
//}

Solution

  • I get a javascript error with your code: Uncaught TypeError: document.getElementByClassName is not a function. document.getElementByClassName doesn't exist. The name of the function is document.getElementsByClassName (plural), and it returns an array of DOM Elements. Process through the array adding click listeners (or use jQuery with an appropriate selector). Also, this.value is not a function (change this.value() to this.value).

    var elems = document.getElementsByClassName('address');
    for (var i = 0; i < elems.length; i++) {
      elems[i].addEventListener('click', function() {
        geocodeAddress(this.value, geocoder, map);
      });
    };
    
    function geocodeAddress(address, geocoder, resultsMap) {
      geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status === 'OK') {
          resultsMap.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }
    

    proof of concept fiddle

    code snippet:

    var geocoder;
    
    function initMap() {
      geocoder = new google.maps.Geocoder();
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: {
          lat: 37.4419,
          lng: -122.1419
        }
      });
    
      var elems = document.getElementsByClassName('address');
      for (var i = 0; i < elems.length; i++) {
        elems[i].addEventListener('click', function() {
          geocodeAddress(this.value, geocoder, map);
        });
      };
    }
    
    function geocodeAddress(address, geocoder, resultsMap) {
      geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status === 'OK') {
          resultsMap.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }
    
    google.maps.event.addDomListener(window, "load", initMap);
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px;
    }
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <div id="floating-panel">
      <input id="address-1" class="address" value="Paris" type="button" />
      <input id="address-2" class="address" value="London" type="button" />
      <input id="address-3" class="address" value="New York" type="button" />
    </div>
    <div id="map"></div>