Question

I am working with Google Maps embedded on my webpage. What I want is to create a button click event, so then after a user has entered an address into a textbox called txtBoxMaps, they can click a button which will display the new location. I tried using: google.maps.event.addDomListener(window, 'click', Initialize); but it doesnt seem to do anything.

Here is my code below:

<script type="text/javascript">

function Initialize() {

var mapOptions = {
            center: new google.maps.LatLng(-33.01, 27.9),
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('GMap1'), mapOptions);

        var input = document.getElementById('txtBoxMaps');

        });

    }

    google.maps.event.addDomListener(window, 'load', Initialize);



</script>



<input type="text" id="txtBoxMaps"/>

        <div id="GMap1" style="height: 240px; width:570px" ></div>
Was it helpful?

Solution

You'll need to put the listener on the button, and then get the value in the field at that point, like so, using your code: var input = document.getElementById('txtBoxMaps').value;

At that point you can geocode that address, and set the center of the map to the new location.

function getGeocode() {
  var input = document.getElementById("txtBoxMaps").value;
  geocoder.geocode( { 'address': input}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
    }
  });

See the documentation on geocoding here: https://developers.google.com/maps/documentation/javascript/geocoding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top