Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API 3 search box

I cannot figure out how to implement the search box in my google maps. I have it where the user can pick some stuff from a form and it loads the markers on the map. Now I want to add where they can type in the city and state using the google search box, like on maps.google.com. Can this be done with API v. 3?

like image 322
shinjuo Avatar asked Sep 01 '11 18:09

shinjuo


1 Answers

There is no complete "widget" in Google maps for this task. But it is easy to accomplish it. In HTML you can have a text field and a button "Search". (Instead you can handle the Enter key in the text field).

<input type="text" id="search_address" value=""/>
<button onclick="search();">Search</button>

In Javascript you instantiate and use a Geocoder:

var addressField = document.getElementById('search_address');
var geocoder = new google.maps.Geocoder();
function search() {
    geocoder.geocode(
        {'address': addressField.value}, 
        function(results, status) { 
            if (status == google.maps.GeocoderStatus.OK) { 
                var loc = results[0].geometry.location;
                // use loc.lat(), loc.lng()
            } 
            else {
                alert("Not found: " + status); 
            } 
        }
    );
};
like image 195
Jiri Kriz Avatar answered Nov 08 '22 05:11

Jiri Kriz