根据 Google Places API 服务中的地名、城市名称和地址获取地点 ID

Asi*_*eed 0 api google-places-api

我正在使用 Google Places API 服务(https://developers.google.com/places/web-service/)根据位置名称获取地点 ID。用户键入一些位置名称,就会出现相关建议,用户可以从中选择并获取地点 ID。我有一个要求,我需要三个文本框和一个按钮。用户输入地名、城市名和地址,然后单击按钮获取 placeId。目前,我没有看到基于多个参数获取地点 ID 的选项。我怎样才能做到这一点?

Reb*_*ose 5

文本搜索请求接受查询字符串。一种可能的解决方案是允许用户在不同的文本字段中输入地名、城市和地址,然后在发送 ajax 请求之前将所有这些内容连接到一个查询字符串中。

你的表格看起来像这样:

<form id="form">
  <input type="text" name="place" value="">
  <input type="text" name="city" value="">
  <input type="text" name="address" value="">
  <input type="submit" value="Locate">
</form>
Run Code Online (Sandbox Code Playgroud)

你的 JavaScript 看起来像这样:

$( "#form" ).submit(function( event ) {

  // concatenate places into a single query string
  var query = $('input[name="place"]').val() + $('input[name="city"]').val() + $('input[name="address"]').val();

  // convert spaces to '+' symbol for query
  query = encodeURIComponent(query);

  // send ajax request
  $.ajax({url: "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + query + "&key=YOUR_API_KEY", success: function(result){
        alert('success, now retrieve your id from result variable');
    }});

  //prevent the submit button from reloading the page
  event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)