Is there a way to restrict the Google Places Autocomplete to search a city's streets?

前端 未结 4 724
天命终不由人
天命终不由人 2021-02-05 21:10

Can I restrict the search to a city\'s streets when using the Google Places Autocomplete?

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 21:42

    I was looking for a way to restrict Places Autocomplete to street_number level but didn't find one.

    The best solution I could come up with is to check for the street_number component in the places result and present a notification to the user if it was missing.

    Example code:

    var searchbox = document.getElementById('location');
    
    var options = {             
        types: ['geocode']
    };
    
    autocomplete = new google.maps.places.Autocomplete(searchbox, options);
    
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
    
            var foundStreet = false;
    
            for (var i = 0; i < place.address_components.length; i++) {
                var c = place.address_components[i];
    
                for (var j = 0; j < c.types.length; j++) 
                {
                    if (c.types[j] == "street_number")
                    {
                        foundStreet = true;
                        break;
                    }
                }
    
                if (foundStreet)
                    break;
            }
    
            if (!foundStreet)
                alert("Not a valid street number, add some pretty message to the user.");
    
            console.log(place);
        });
    

提交回复
热议问题