0

I am learning to use Google Geolocation API. I have got my key and I am just trying to make a simple form which takes the city name and returns me the latitude and longitude using Geolocation API.

The simple form is :

<!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>

Can anyone tell me how to use the Geolocation API in a way that I can retrieve the latitude and longitude of the entered city.

Akshay
  • 77
  • 1
  • 11

1 Answers1

1

Daily limit without API Key is 2500. You can read my question - Where to place API key for Google Geocoding API?

If you just use Geocoding on client browser, you do not need Google API Key. You can still pass the key if your client is a heavy user and you want to pay on behalf of your client.

Here is the working demo - 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>
Win
  • 61,100
  • 13
  • 102
  • 181
  • so as of now, we are required to include an API for whatever request made, do you have any updated solution on this? – seraph Sep 16 '21 at 20:25
  • Also, I believe that the geolocation and geocoding are now separate feature that serves different purpose. (geolocation: locating user, geocoding: give coordinate based on address and vice versa) – seraph Sep 16 '21 at 20:27