The Wayback Machine - https://web.archive.org/web/20241118120000/https://www.geeksforgeeks.org/google-geo-coding-web-service-json-response/
Open In App

Google Geo-coding Web Service (JSON response)

Last Updated : 14 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : JSON Formatting in Python Google has an excellent web service that allows us to make use of their large database of geographic information. Here, we are going to be working with the Google Maps API. In the old days, this Maps API was free and did 2, 500 requests per day but now they’ve made it so that parts of it are behind API keys and you start having to use OAuth and stuff. We can submit a geographical search string like “Ann Arbor, MI” to their geocoding API and have Google return its best guess as to where on a map we might find our search string and tell us about the landmarks nearby. The geocoding service is free but rate limited so you cannot make unlimited use of the API in a commercial application. But if you have some survey data where an end user has entered a location in a free-format input box, you can use this API to clean up your data quite nicely. When you are using a free API like Google’s geocoding API, you need to be respectful in your use of these resources. If too many people abuse the service, Google might drop or significantly curtail its free service. You can read the online documentation for this service, but it is quite simple and you can even test it using a browser by typing the following URL into your browser: http://maps.googleapis.com/maps/api/geocode/json?address=Ann+Arbor%2C+MI

Make sure to unwrap the URL and remove any spaces from the URL before pasting it into your browser. The following is a simple application to prompt the user for a search string, call the Google geocoding API, and extract information from the returned JSON. 

Python3




# Libraries used to grab the URL web stuff and import json
import urllib.request, urllib.parse, urllib.error
import json
 
# Note that Google is increasingly requiring keys
# for this API
# service URL for Google Maps API
 
while True:
    address = input('Enter location: ')
    if len(address) < 1: break
     
    # Concatenate the serviceurl and urllib.parse.urlencode
    # which give a dictionary of address equal and this bit
    # right here
    url = serviceurl + urllib.parse.urlencode(
        {'address': address})
 
    print('Retrieving', url)
 
    # urlopen() to get a handle
    uh = urllib.request.urlopen(url)
    # Read the whole document in UTF-8
    data = uh.read().decode()
    print('Retrieved', len(data), 'characters')
 
    # Load internal strings
    try:
        js = json.loads(data)
    except:
        js = None
    # If false then quit and print data
    if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue
     
    # Call json dump and print it with an indent of four
    print(json.dumps(js, indent = 4))
     
    # Parsing and printing
    lat = js["results"][0]["geometry"]["location"]["lat"]
    lng = js["results"][0]["geometry"]["location"]["lng"]
    print('lat', lat, 'lng', lng)
    location = js['results'][0]['formatted_address']
    print(location)


Output :

Enter location: Dehradun
Retrieving http://maps.googleapis.com/maps/api/geocode/json?address=dehradun
Retrieved 1743 characters
{
    "results": [
        {
            "address_components": [
                {
                    "long_name": "Dehradun",
                    "short_name": "Dehradun",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Dehradun",
                    "short_name": "Dehradun",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "Uttarakhand",
                    "short_name": "UK",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "India",
                    "short_name": "IN",
                    "types": [
                        "country",
                        "political"
                    ]
                }
            ],
            "formatted_address": "Dehradun, Uttarakhand, India",
            "geometry": {
                "bounds": {
                    "northeast": {
                        "lat": 30.4041936,
                        "lng": 78.1089305
                    },
                    "southwest": {
                        "lat": 30.2466633,
                        "lng": 77.92533879999999
                    }
                },
                "location": {
                    "lat": 30.3164945,
                    "lng": 78.03219179999999
                },
                "location_type": "APPROXIMATE",
                "viewport": {
                    "northeast": {
                        "lat": 30.4041936,
                        "lng": 78.1089305
                    },
                    "southwest": {
                        "lat": 30.2466633,
                        "lng": 77.92533879999999
                    }
                }
            },
            "place_id": "ChIJr4jIVsMpCTkRmYdRMsBiNUw",
            "types": [
                "locality",
                "political"
            ]
        }
    ],
    "status": "OK"
}
lat 30.3164945 lng 78.03219179999999
Dehradun, Uttarakhand, India

The program takes the search string and constructs a URL with the search string as a properly encoded parameter and then uses urllib to retrieve the text from the Google geocoding API. Unlike a fixed web page, the data we get depends on the parameters we send and the geographical data stored in Google’s servers. Once we retrieve the JSON data, we parse it with the json library and do a few checks to make sure that we received good data, then extract the information that we are looking for.



Previous Article
Next Article

Similar Reads

How to intercept response.send() / response.json() in Express JS
In the context of Express , "intercept" usually refers to the process of capturing or modifying a request or response in a middleware function before it reaches its final destination (e.g., a route handler) or before it is sent back to the client. In Express, intercepting response.send() or response.json() can be achieved by using middleware functi
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
Geo Information in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Electron provides us with a way by which we can fe
5 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which he
2 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
How to get JSON response in Ajax ?
AJAX is a set of technologies that allows users to fetch data asynchronously without interfering with the existing page. We can fetch various types of data using AJAX like JSON, XML, HTML, and text files. In this article, we will see how to get JSON response in Ajax. Approach: To solve this problem, we will first consider a JSON file named "capital
4 min read
How to convert camel case to snake case in JSON response implicitly using Node.js ?
Camel case and snake case are two common conventions for naming variables and properties in programming languages. In camel case, compound words are written with the first word in lowercase and the subsequent words capitalized, with no spaces or underscore between them. For example, firstName is written in camel case. In snake case, compound words
5 min read
Scraping a JSON response with Scrapy
Scrapy is a popular Python library for web scraping, which provides an easy and efficient way to extract data from websites for a variety of tasks including data mining and information processing. In addition to being a general-purpose web crawler, Scrapy may also be used to retrieve data via APIs. One of the most common data formats returned by AP
2 min read
response.json() - Python requests
Python requests are generally used to fetch the content from a particular resource URL. Whenever we make a request to a specified URL through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.json() out of a r
3 min read
How to read Array of Nested JSON Response in Postman ?
We know that the postman is the one who delivers the letters sent by your friends, colleagues, or relatives and acts as a bridge of communication. Here Postman refers to the development of API that acts as a bridge or communication between different programs. In other words, it is an API client, made for developing, testing, and management. You can
3 min read
How to Check if the Response of a Fetch is a JSON Object in JavaScript?
In JavaScript, when making HTTP requests using the Fetch API, it's common to expect JSON data as a response from the server. However, before working with the response data, it's essential to verify whether it is indeed a JSON object or not. The below approaches can help you to check if the response is in JSON format or not: Table of Content By usin
2 min read
Creating a JSON Response Using Django and Python
In Django, we can give responses to the front end in several ways. The simplest way to render a template or send a JSON response. JSON stands for JavaScript Object Notation and is widely used for data transfer between front-end and back-end and is supported by different languages and frameworks. In Django, we can easily give a JSON response to the
4 min read
How to Send JSON Response using Node.js ?
NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features. During production, several times we need to send the resources or some type of information as a response, and javascript object notation (JSON) syntax is widely used t
5 min read
Automated Time-Based Reload Response in Java Web Servlet
Automated Time-Based Reload Response in Java Web Servlet comes into the picture while working with Java Servlets, we need a mechanism for page auto-reload according to our need. This automated refresh can be created in the Java servlet itself as a response. In webpages, there is a need where without clicking any button or link, the page should be a
2 min read
Difference Between Web 1.0, Web 2.0, and Web 3.0
Web 1.0 was all about fetching, and reading information. Web 2.0 is all about reading, writing, creating, and interacting with the end user. It was famously called the participative social web. Web 3.0 is the third generation of the World Wide Web, and is a vision of a decentralized web which is currently a work in progress. It is all about reading
8 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
Best Practices for Secure Coding in Web Applications
Web applications are essential for corporations to deliver digital offerings, and they have got grow to be increasingly important in recent years as increasingly human beings get proper access to offerings online. However, with the upward push of cyber-assaults and data breaches, it’s vital to put in force web software safety best practices to prot
6 min read
Deploying Your Web App using Azure App Service
Pre-requisite: Introduction to Microsoft Azure | A cloud computing service The majority of Computer Science students start with Web Development or Machine Learning. Now after learning how to create a website, we should learn to deploy it online. By deploying our website, we can share it with others, perform alpha or beta testing, perform live chang
4 min read
Difference between WCF and Web Service
WCF (Windows Communication Foundation): WCF, as the name suggests, is a unified .NET framework that is used to develop service-oriented applications. It allows you to develop applications that can communicate using different communication mechanisms. It is founded for other Microsoft Distributed Technologies and considered the future of distributed
3 min read
Amazon Web Services - Simple Notification Service(SNS): Complete Setup,Pricing,Features
Amazon Web Services Simple Notification Service (AWS SNS) is a web service that automates the process of sending notifications to the subscribers attached to it. SNS provides this service to both application-to-person and application-to-application. It uses the publishers/subscribers paradigm for the push and delivery of messages. The data loss is
9 min read
Practice Tags :
three90RightbarBannerImg