Google 地理位置 API

Google Geolocation API

我正在学习使用 Google 地理定位 API。我拿到了我的钥匙,我只是想制作一个简单的表格,它使用城市名称 returns 我使用地理定位 API.

我的纬度和经度

简单的形式是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<form>
    <fieldset>
        <ul>

            <li>
                <label for="city-search">City Name</label>
                <input type="text" id="city-search" placeholder="e.g. Rochester, NY">
            </li>

        </ul>

    </fieldset>

    <input type="button" id="sub" value="Submit" onclick="geolocation()">


</form>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src="geolocation.js"></script>

</body>
</html>

谁能告诉我如何使用地理定位 API 来检索输入城市的经纬度。

没有API键的每日限额是2500。你可以阅读我的问题 - Where to place API key for Google Geocoding API?

如果您只是在客户端浏览器上使用地理编码,则不需要 Google API 密钥。 如果您的客户是重度用户并且您想代付,您仍然可以传递密钥。

这是工作演示 - https://jsfiddle.net/uj5qcqx0/

$(function() {
  $('#sub').click(function() {
    var city = $('#city-search').val();
    if (city.length) {
      var url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + city;
      $.get(url, function(data) {       
        $("#result").text(JSON.stringify(data));        
      });
    } else {
      alert("Please enter city.");
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="city-search">City Name</label>
<input type="text" id="city-search" placeholder="e.g. Rochester, NY">

<input type="button" id="sub" value="Submit">

<div id="result"></div>