为什么在输入地址上使用 getPlace() 时谷歌自动完成返回未定义

2024-01-07

为什么谷歌在使用自动完成功能时不返回带有格式化地址的对象以及如何获取格式化地址?

When I log the variable from_place it returns an object like so: enter image description here

but when I log to_place it returns an object with formatted_address: enter image description here

我意识到我在第一个表单上使用自动完成功能,这会影响它,但我如何才能不影响或给我格式化的地址?

// declare variables
var map, infoWindow, placeSearch, autocomplete;

// autocomplete form
var componentForm = {
    locality: "short_name",
    postal_code: "short_name"
};
// autocomplete form

// init google map API's
function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 6
    });
    infoWindow = new google.maps.InfoWindow();

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                // console.log(pos)
                infoWindow.setPosition(pos);
                infoWindow.setContent("Location found.");
                infoWindow.open(map);
                map.setCenter(pos);
            },
            function() {
                handleLocationError(true, infoWindow, map.getCenter());
            }
        );
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
    google.maps.event.addDomListener(window, "load", function() {
        autocomplete = new google.maps.places.Autocomplete(
            document.getElementById("from_places"),
            { types: ["geocode"] }
        );
        var to_places = new google.maps.places.Autocomplete(
            document.getElementById("to_places")
        );
        google.maps.event.addListener(autocomplete, "place_changed", function() {
            // var from_place needs to return an object with a formatted adress
            var from_place = autocomplete.getPlace();
            console.log(from_place);
            var from_address = from_place.formatted_address;
            $("#origin").val(from_address);
        });
        google.maps.event.addListener(to_places, "place_changed", function() {
            var to_place = to_places.getPlace();
            console.log(to_place);
            var to_address = to_place.formatted_address;
            
            $("#destination").val(to_address);
        });
        autocomplete.setComponentRestrictions({
            country: ["uk"]
        });
        to_places.setComponentRestrictions({
            country: ["uk"]
        });

        // Avoid paying for data that you don't need by restricting the set of
        // place fields that are returned to just the address components.
        autocomplete.setFields(["address_component"]);

        // When the user selects an address from the drop-down, populate the
        // address fields in the form.
        autocomplete.addListener("place_changed", fillInAddress);
    });

    // add all functions related to google in here

    // collection to drop off
    var directionsService = new google.maps.DirectionsService();
    var directionsRenderer = new google.maps.DirectionsRenderer();
    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 7,
        center: { lat: 41.85, lng: -87.65 }
    });
    directionsRenderer.setMap(map);

    var onChangeHandler = function() {
        calculateAndDisplayRoute(directionsService, directionsRenderer);
    };
    // One destination must be set at anyone time because
    // 70 InvalidValueError: in property destination: must set one of location, placeId or query
    document
        .getElementById("googleAlgorithm2")
        .addEventListener("click", onChangeHandler);

    function calculateAndDisplayRoute(directionsService, directionsRenderer) {
        directionsService.route(
            {
                origin: {
                    query: document.getElementById("from_places").value
                },
                destination: {
                    query: document.getElementById("to_places").value
                },
                travelMode: "DRIVING",
                drivingOptions: {
                    departureTime: new Date(/* now, or future date */),
                    trafficModel: "pessimistic"
                    //    departureTime: new Date(/* now, or future date */),
                }
            },
            function(response, status) {
                if (status === "OK") {
                    directionsRenderer.setDirections(response);
                } else {
                    window.alert("Directions request failed due to " + status);
                }
            }
        );
    }

    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(
        browserHasGeolocation
            ? "Error: The Geolocation service failed"
            : "Error Your browser does not support geolocation."
    );
    infoWindow.open(map);
}

function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
        document.getElementById(component).value = "";
        document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details,
    // and then fill-in the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
        }
    }
}


如果你想要formatted_address返回后,您需要指定该字段。

代替:

// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(["address_component"]);

Do:

autocomplete.setFields(["address_component", "formatted_address"]);

你只是打电话setFields在您的自动完成输入之一上。如果你不调用它,你就会得到(并付费)all中的字段地点结果 https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/reference/places-service#PlaceResult

概念证明小提琴 https://jsfiddle.net/geocodezip/sfn93x2r/

// This sample uses the Autocomplete widget to help the user select a
// place, then it retrieves the address components associated with that
// place, and then it populates the form fields with those details.
// This sample requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var placeSearch, autocomplete;

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById('autocomplete'), {
      types: ['geocode']
    });

  // Avoid paying for data that you don't need by restricting the set of
  // place fields that are returned to just the address components.
  autocomplete.setFields(['address_component', 'formatted_address']);

  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  document.getElementById('formatted_address').innerHTML = "formatted_address:<br>" + place.formatted_address;
  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

</style><link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"><style>#locationField,
#controls {
  position: relative;
  width: 480px;
}

#autocomplete {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 99%;
}

.label {
  text-align: right;
  font-weight: bold;
  width: 100px;
  color: #303030;
  font-family: "Roboto";
}

#address {
  border: 1px solid #000090;
  background-color: #f0f9ff;
  width: 480px;
  padding-right: 2px;
}

#address td {
  font-size: 10pt;
}

.field {
  width: 99%;
}

.slimField {
  width: 80px;
}

.wideField {
  width: 200px;
}

#locationField {
  height: 20px;
  margin-bottom: 2px;
}
<div id="locationField">
  <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text" />
</div>
<div id="formatted_address"></div>

<!-- Note: The address components in this sample are typical. You might need to adjust them for
           the locations relevant to your app. For more information, see
     https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->

<table id="address">
  <tr>
    <td class="label">Street address</td>
    <td class="slimField"><input class="field" id="street_number" disabled="true" /></td>
    <td class="wideField" colspan="2"><input class="field" id="route" disabled="true" /></td>
  </tr>
  <tr>
    <td class="label">City</td>
    <td class="wideField" colspan="3"><input class="field" id="locality" disabled="true" /></td>
  </tr>
  <tr>
    <td class="label">State</td>
    <td class="slimField"><input class="field" id="administrative_area_level_1" disabled="true" /></td>
    <td class="label">Zip code</td>
    <td class="wideField"><input class="field" id="postal_code" disabled="true" /></td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="3"><input class="field" id="country" disabled="true" /></td>
  </tr>
</table>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在输入地址上使用 getPlace() 时谷歌自动完成返回未定义 的相关文章

  • Google 地图上的自定义路线/路径/道路

    我需要能够使用 V2 或 V3 最好是 3 创建在某种意义上忽略建筑物的路径 我试图创建一个 kml 文件来自己绘制所有路径 然后找到某种方法根据需要打开 关闭它们 例如 用户想要从 A 点前往 B 点 这些点之间有许多建筑物 用户可以实际
  • 如何将 Live API for Contacts 的响应中的哈希值转换为文本

    我集成了 Live JS api 来获取用户的实时联系人 它以哈希格式 email hash 返回电子邮件 我如何使用 javascript 或 c net 转换为可读文本 非常感谢 我遇到了同样的问题 并且找到了解决方案 您所需要做的就是
  • Trello API - 未经授权的权限请求

    我正在尝试编写一个小脚本来更新卡的当前列表中的时间量 以便我们可以优化吞吐量 我在 jsfiddle 上写了一个小脚本 几乎可以工作 但我得到了一个 请求未经授权的卡许可 当尝试使用时 Trello post cards card id a
  • 415 不支持的媒体类型; Angular2 到 API

    我是 Angular 2 的新手 我面临着一个无法找到解决方案的问题 当我尝试从 Angular 2 发布到 API 时 我得到 415 不支持的媒体类型 角度2代码 onSubmit value any console log value
  • 414 请求 URI 太大错误 Google 地图 v3

    当我调用构造函数来创建具有超过 15 个不同 KMZ 文件的新 KmlLayer 时 似乎会发生此错误 构造函数的调用是 var layer new google maps KmlLayer http 我每次都可以使用 15 个不同的 KM
  • Google 地图 InfoBubble PixelOffset(从标记上方的默认位置移动)

    我正在尝试实现一个自定义 infoBubble 它的框打开到标记的侧面 而不是顶部的默认位置 事实证明这比预期的要困难 使用普通的infoWindow 您可以使用pixelOffset 请参阅此处文档 https developers go
  • Twitter 的推文按钮有回调吗?

    有没有办法在 Twitter 的推文按钮上注册回调 我希望能够跟踪我网站上的哪些特定用户在 Twitter 上发布了链接 我无法添加 onClick 事件 因为它是跨域 iFrame 还有其他想法吗 我见过一种方法 https stacko
  • Android GCM 服务器的 API 密钥

    我有点困惑我应该为 GCM 服务器使用哪个 API 密钥 在文档中它说使用 android api 密钥 这对我不起作用并且总是给出未经授权的 http developer android com google gcm gs html ht
  • 从 DirectionsRenderer 中获取折线或标记的事件

    我正在使用 DirectionsService 和路线方法来生成 DirectionsResult 我还使用 DirectionsRenderer 对象来显示结果 因为它非常易于使用 我在检测 Directions changed 事件时没
  • SSDT SQL Server 数据库项目中用于架构比较的命令行/API?

    在 Visual Studio 2012 中 我们有Schema Compare http msdn microsoft com en us library hh272690 28v vs 103 29 aspx in SSDT http
  • 谷歌地图 API 没有密钥?

    如何在没有密钥的情况下使用 Google Maps v3 API 我在里面见过这个例子 http www birdtheme org useful v3largemap html但无法弄清楚具体是什么导致它不出错 编辑 如果有人建议 Sta
  • 使用 Ruby 的“open-uri”打开 utf-8 URI 时遇到问题

    我正在尝试使用 ruby 和 open uri 从谷歌地图网络服务 API 获取丹麦位置地址 试图得到丹麦艾勒 http maps googleapis com maps api geocode json address r sensor
  • Google 地图 v3 自定义标记图标无法保持其在地图上的位置

    使用 Google 地图 v3 进行开发 由于某种原因 我的自定义标记图标 更改 了它在放大时的位置 看起来它有某种 填充 属性 不会随着缩放而改变 这意味着它在最大缩放 18 上的位置是正确的 但是如果我更改缩放值 它会 移动 一点到顶部
  • 简单、安全的API认证系统

    我有一个简单的 REST JSON API 供其他网站 应用程序访问我网站的一些数据库 通过 PHP 网关 基本上该服务的工作原理如下 调用 example com fruit orange 服务器返回有关橙子的 JSON 信息 问题是 我
  • 使用 Django 在 Google 地图上放置标记

    我正在尝试使用 API 和 HTML5 地理位置根据 Google 地图上模型中存储的纬度和经度放置标记 问题是如何使用模板关键字循环遍历 JavaScript 标签中存储的每个对象的经纬度信息 我不认为这可以在 Django 中完成 我在
  • Google 将自动完成功能放置在 React 组件中

    我正在尝试构建一个谷歌地图组件 谷歌地图 API v3 一切正常 但自动完成功能不行 这是我正在使用的代码 Google 地图组件 import React Component from react import ReactDOM from
  • 将 CURL 命令行转换为 VBA

    在 CURL 中 我可以使用这一行 curl data DataToBeSent https example com resource cgi 我正在努力将此类行转换为在 VBA 中使用 这是我到目前为止的尝试 Sub POST Metho
  • 循环选项在 youtube js api 中不起作用

    我想知道为什么我的代码不循环播放视频 除了循环选项之外 一切正常 我真的需要它 多谢 div You need Flash player 8 and JavaScript enabled to view this video div
  • 如何使用谷歌地图检测一个点是否在多边形内部?

    我想检测到google maps LatLng是在一个里面google maps Polygon 我怎样才能做到这一点 Cheers 你可以使用这个谷歌地图V3 google maps geometry poly containsLocat
  • 使用 AngularJS 动态加载 Google 地图 API

    我正在尝试使用 AngularJS 加载 Google Maps API 以及该部分的控制器 search controller GoogleMaps scope sce function GoogleMaps scope sce var

随机推荐