Search code examples
javascriptgoogle-mapsgoogle-geocodergoogle-geolocation

Get Address by Element Attribute


I've some divs and each data-id has an specific address. Then I'm trying to get the data-id value from the clicked div and set on de geocode to center the map on the address. But I couldn't figure it out how to make it on click.

My code so far:

<div class="map">

  <div class="btn_mapa" id="1" data-id="San Diego, CA"></div>
  <div class="btn_mapa"  id="2" data-id="Belo Horizonte, MG"></div>
  <div class="btn_mapa"  id="3" data-id="New York, NY"></div>
  <!–– ... many others ... ––>
  <div class="btn_mapa"  id="259" data-id="Atlanta, GA"></div>

  <div id="map-canvas" style="width: 100%; height: 100%;"></div>

</div>


<script src="https://maps.googleapis.com/maps/api/js?key=MYAPI"></script>

<script>

var geocoder;
var map;
var div1 = document.getElementById("1");
var address = div1.getAttribute("data-id");

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

  if (geocoder) {
    geocoder.geocode({
      address: address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Solution

  • add click listeners to all the <div>'s with class btn_mapa, in that click listener function (this is a reference to the clicked <div>), get the data-id attribute of the <div> and geocode it:

    var btn_mapa = document.getElementsByClassName('btn_mapa');
    for (var i=0; i<btn_mapa.length; i++) {
      google.maps.event.addDomListener(btn_mapa[i], 'click', function() {
      var address = this.getAttribute('data-id');
      console.log(address);
      geocodeAddress(address);
      });
    }
    function geocodeAddress(address) {
      if (geocoder) {
      geocoder.geocode({
        address: address
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
            map.setCenter(results[0].geometry.location);
    
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
    

    }

    proof of concept fiddle

    code snippet:

    #map-canvas {
      height: 80%;
    }
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div class="map">
      <div class="btn_mapa" id="1" data-id="San Diego, CA">San Diego</div>
      <div class="btn_mapa" id="2" data-id="Belo Horizonte, MG">Belo Horizonte</div>
      <div class="btn_mapa" id="3" data-id="New York, NY">New York, NY</div>
      <!–– ... many others ... ––>
      <div class="btn_mapa" id="259" data-id="Atlanta, GA">Atlanta, GA</div>
    </div>
    <div id="map-canvas"></div>
    <script>
      var geocoder;
      var map;
      var div1 = document.getElementById("1");
      var address = div1.getAttribute("data-id");
    
      function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
          zoom: 8,
          center: latlng,
          mapTypeControl: true,
          mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
          },
          navigationControl: true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
        var btn_mapa = document.getElementsByClassName('btn_mapa');
        for (var i = 0; i < btn_mapa.length; i++) {
          google.maps.event.addDomListener(btn_mapa[i], 'click', function() {
            var address = this.getAttribute('data-id');
            console.log(address);
            geocodeAddress(address);
          });
        }
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    
      function geocodeAddress(address) {
        if (geocoder) {
          geocoder.geocode({
            address: address
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
              } else {
                alert("No results found");
              }
            } else {
              alert("Geocode was not successful for the following reason: " + status);
            }
          });
        }
      }
    </script>