更改谷歌地图自动完成文本框中的值 [英] Change the value in textbox of a google map autocomplete

查看:17
本文介绍了更改谷歌地图自动完成文本框中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 javascript 代码,它在作为地址一部分的不同输入文本框上执行谷歌地图自动完成.

I have the following javascript code which does google map autocomplete on different input textboxes that are parts of an address.

function startAutoComplete() {
    var address = document.getElementById("addressId");
    var city = document.getElementById("cityId");
    var state = document.getElementById("stateId");
    var zip = document.getElementById("zipId");

    //option for autocomplete
    var option = {types: ['geocode'], componentRestrictions: {country: 'us'}};

    //autocomplete for address textbox
    autocomplete = new google.maps.places.Autocomplete(address, option);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();

        //parses the result object and populates the other textboxes accordingly
        for(i=0; i<place.address_components.length; i++)
        {
            if(place.address_components[i].types[0] == 'locality')
            city.value = place.address_components[i].long_name;

            if(place.address_components[i].types[0] == 'administrative_area_level_1')
            state.value = place.address_components[i].short_name;

            if(place.address_components[i].types[0] == 'postal_code')
            zip.value = place.address_components[i].long_name;
        }

        /* Here is the PROBLEM */
        address.value = place.name;

    });

但是,当我尝试使用完整地址的缩短版本更新正在自动完成的文本框时(所以这里只是街道号码和街道名称).完整地址文本框中的值不会更改.我尝试使用 jquery 并在文本框上使用 setAttribute() 设置 value 属性.我做错了什么?

However when I try and update the textbox that is being auto completed with a shortened version of the full address (so here just the street number and street name). The value in the full address textbox doesn't change. I've tried using jquery and setting the value attribute with setAttribute() on the textbox. What am I doing wrong?

推荐答案

我发现以编程方式更改自动完成输入值的最简单方法是重新初始化输入字段.

The simplest way I've found to programmatically change the value of an Autocomplete input is to reinitialize the input field.

autocomplete = new google.maps.places.Autocomplete(address, option);

google.maps.event.addListener(autocomplete, 'place_changed', function() {
   // populate your other text fields
   ...
   // change the value of your autocomplete
   address.value = place.name;
   // reinitialize with new input value
   autocomplete = new google.maps.places.Autocomplete(address, option);
}

这篇关于更改谷歌地图自动完成文本框中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆