Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geocoding location from input box

I'm new to google maps and simply trying to get the hang of it. I want to be able to type in a city or address, and then have the map load it and place a marker.

Right now my map loads fine initially, but when I type in a city or address nothing happens. Any idea what's going on here?

<script type="text/javascript">
var geocoder;
var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlang = new google.maps.LatLng(42, -84);
    var myOptions = {
        center: latlang, zoom: 5, mapTypeId: google.maps.MapTypeId.SATELLITE,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
  }

  function codeAddress() { 
    var sAddress = document.getElementById("newLocation").value;
    geocoder.geocode( { 'address': sAddress}, function(results, status) { 
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
                });
            }
            else{
            alert("Geocode was not successful for the following reason: " + status);
            }
        });
  }
</script>
</head>
  <body onload="initialize()">
    Address: <input type="text" id="newLocation" style=" width:200px" title="Address to Geocode" />     
    <input type="button" onclick="codeAddress()" id="inputButtonGeocode" style="width:150px" title="Click to Geocode" value="Geocode" />
    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>
like image 918
user1406951 Avatar asked Aug 01 '26 22:08

user1406951


1 Answers

In the line

var map = new google.maps.Map(document.getElementById("map_canvas")...

remove the word var. Because it creates map in a functionally local scope and the geocoding function only sees the prior (empty) map variable. By removing it the global map variable is updated to this new google map.

like image 153
Tina CG Hoehr Avatar answered Aug 03 '26 14:08

Tina CG Hoehr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!