javascript - 为什么 Google Places API 不执行我的请求?

标签 javascript html google-places-api

我正在尝试创建一个简单的应用程序,在其中插入搜索区域、搜索内容和搜索半径。我不明白为什么它只在我第二次执行查询搜索时才能正常工作,我知道问题可能出在我的 codeAddress() 函数中:

function codeAddress(){
                var address = document.getElementById('Zona').value;
                geocoder.geocode( { 'address': address}, function(results, status){
                    if (status == google.maps.GeocoderStatus.OK){
                    map.setCenter(results[0].geometry.location);
                    coordo = results[0].geometry.location;
                    }else{
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }

由于某种原因,我不知道它会跳过并且不会进入 geocoder.geocode( { 'address': address}, function(results, status) 但是相反,如果这是我第二次执行该函数,而不是第一次,它就会进入内部。

这是应用程序:

Jsfiddle 如果您输入城市名称并单击按钮一次,它就会找到位置,如果您再次单击按钮,它会按预期工作,它会掉落图钉并创建表格......有人知道为什么吗?谢谢。

最佳答案

我查看了您的代码,正如您所说,函数 codeAddress 第一次跳转。 我在 Google 网站开发人员上查找了地理编码服务的操作,发现函数 codeAddress 的行为与您的相同。

为了解决您的问题,我认为您可能会在地理编码之前和启动功能搜索之后运行。

为此,我想我会使用 jQuery 更改:

$ ("input"). change (function () {
        //your code here
     })

你的函数应该是这样的:

    $(document).ready(function(){
        $("#Zona").change(function codeAddress(){
            var address = document.getElementById('Zona').value;
            geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': address}, function(results, status){
                if (status == google.maps.GeocoderStatus.OK){
                    coordo=(results[0].geometry.location);
                }else{
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
        });
    });

我用我的更改修改了您的示例,您可以在此处查看: http://jsfiddle.net/ftxgm0cn/

关于javascript - 为什么 Google Places API 不执行我的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30377000/

相关文章:

javascript - Webpack - 导出方法如何影响 Tree Shaking?

javascript - ag-grid如何更改分页按钮文本

javascript - 法语字符 html - javascript

google-places-api - 从 Google Maps CID 到 Place ID

javascript - 生成随机字符串并检查数据库以确保不重复

html - 在同一个元素上延迟和不延迟?

html - SVG 不会垂直居中

javascript - Meteor:多个提交表单或任何可以让我从模板中提取数据的事件?

ios - 即使条件完成后,For 循环仍会迭代解析 JSON

ios - 适用于 iOS 版本 3 的 Google 地方信息