0

I have written a small function that will get the user address using the google.maps.event.addListener(). Here is the jsFiddle.

Everything is exactly what I want, apart from when the user finishes typing and focus out from the street field, I just want the street address in the input.

At the moment it looks like this:

now

But I want it to be like this:

enter image description here

Thanks already for help. Cheers.

Subash
  • 7,098
  • 7
  • 44
  • 70

2 Answers2

3

Use a short delay to apply streetAddress

setTimeout(function(){$('#address').val(streetAddress);},50);
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
2

The above solution works great to autocomplete individual address fields. Here's an implementation with options to bias the results, however I'm having problems using bounds to bias the results of the autocomplete field. Here's my jsFiddle.

var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(33.89028890,-117.5617340),
    new google.maps.LatLng(33.7706850,-117.6639850)
);

var updateAddress = {
    autocomplete: new google.maps.places.Autocomplete($("#address")[0], { 
        bounds: defaultBounds,
        types: ['geocode'],
        componentRestrictions: {country: 'us'}
    }),            
    event: function(){
        var self = this;    
        google.maps.event.addListener(self.autocomplete, 'place_changed', function() {
            var place = self.autocomplete.getPlace(),
                address = place.address_components,
                streetAddress = '',
                suburb = '',
                state = '',
                zip = '',
                country = '';

            for (var i = 0; i < address.length; i++) {
                var addressType = address[i].types[0];

                if (addressType == 'subpremise') {
                    streetAddress += address[i].long_name + '/';
                }
                if (addressType == 'street_number') {
                    streetAddress += address[i].long_name + ' ';
                }
                if (address[i].types[0] == 'route') {
                    streetAddress += address[i].long_name;
                }
                if (addressType == 'locality') {
                    suburb = address[i].long_name;
                }
                if (addressType == 'administrative_area_level_1') {
                    state = address[i].long_name;
                }
                if (addressType == 'postal_code') {
                    zip = address[i].long_name;
                }
                if (addressType == 'country') {
                    country = address[i].long_name;
                }
            }

            // update the textboxes
            setTimeout(function(){$('#address').val(streetAddress);},50);
            $('#suburb').val(suburb);
            $('#state').val(state);
            $('#zip').val(zip);
        });

    }
};

updateAddress.event();
Spikolynn
  • 4,067
  • 2
  • 37
  • 44
Jeff
  • 21
  • 1