본문 바로가기
Qt5 Python GUI Programming Cookbook

Using Google Maps

by 자동매매 2023. 2. 28.

In this chapter, you will learn to use Google Maps in Python applications and explore the different advantages provided by Google. You will learn to do the following tasks:

  • Find out details of a location or landmark
  • Get complete information from latitude and longitude values
  • Find out the distance between a two locations
  • Display a location on Google Maps

 

Introduction

The Google Maps API is a set of methods and tools that can be used to find out complete information, including longitude and latitude values, for any location. You can use the Google Maps API methods to find distances between two locations or directions to any location; you can even display Google Maps, marking that location, and much more.

More precisely, there is a Python client library for Google Maps Services. There are several Google Maps APIs, including the Directions API, Distance Matrix API, Geocoding API, Geolocation API, and many more. To use any Google Maps web services, your Python script sends a request to Google; to serve that request, you need an API key. You need to follow these steps to get an API key:

  1. Visit https:/ / console.developers.google.com
  2. Log in to the console using your Google account
  3. Select one of your existing projects or create a new project
  4. Enable the API(s) you want to use
  5. Copy the API key and use it in your Python script

You need to visit the Google API Console, https:/ / console.developers.google.com, and get API keys so that your application is authenticated to work with Google Maps API web services.

API keys help in several ways; first of all, they help identify your application. The API key is included with every request, hence it helps Google monitor your application's API usage, know if your application has consumed its free daily quota, and consequently bill your application too So, in order to use Google Maps API web services in your Python application, you just need to enable the desired API and get a API key for use in your Python application.

 

# install googlemaps module
pip install googlemaps

 

Finding out details of a location or a landmark

In this recipe, you will be prompted to enter a location or landmark whose details you want to know. For example, if you enter Buckingham Palace, the recipe will display the city and postal code of the location where the palace is situated, along with its longitude and latitude values.

demoGoogleMap1.py
0.00MB
demoGoogleMap1.ui
0.00MB

 

 

 

How to do it…

The search method of the GoogleMaps class is the key player in this recipe. The landmark or location entered by the user is passed to the search method. The city, postal_code, lat, and lng properties of the object returned from the search method are used to display the city, postal code, latitude, and longitude of the location, respectively. Let's see how it is done through the following step-by-step procedure:

  1. Create an application based on the Dialog without Buttons template.
  2. Add five QLabel, a QLineEdit, and a QPushButton widget to the form by dragging and dropping six Label, one Line Edit, and a Push Button widget onto the form.
  3. Set the text property of the first Label widget to Find out the Address, Longitude and Latitude and that of the second Label widget to Enter location.
  4. Delete the text property of the third, fourth, and fifth Label widgets, because their text properties will be set through code; that is, the address, longitude, and latitude of the entered location will be fetched through code and will be displayed through these four Label widgets.
  5. Set the text property of the Push Button widget to Search.
  6. Set the objectName property of the Line Edit widget to lineEditLocation.
  7. Set the objectName property of the Push Button widget to pushButtonSearch.
  8. Set the objectName property of the rest of the four Label widgets to labelCity, labelLongitude, and labelLatitude.
  9. Save the application by name as demoGoogleMap1.ui. The form will now appear as shown in the following screenshot:
    The user interface created with Qt Designer is stored in a .ui file and it is an XML file. The XML file is converted into Python code by applying the pyuic5 utility. You can find the generated Python code, demoGoogleMap1.py, in the source code bundle for the book.
  10. Treat the demoGoogleMap1.py script as a header file, and import it into the file from which you will invoke its user interface design.
  11. Create another Python file with the name callGoogleMap1.pyw and import the demoGoogleMap1.py code into it:

 

import sys
from PyQt5.QtWidgets import QDialog, QApplication
import googlemaps
from demoGoogleMap1 import *
class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButtonSearch.clicked.connect(self.displayDetails)
        self.show()
        
    def displayDetails(self):
        address = str(self.ui.lineEditLocation.text())
        
        gmaps = googlemaps.Client(key='AIzaSyC1lNKXkci393EZ1TcD-C9kQWrEUBKNuJI')
        geocode_result = gmaps.geocode(address)
        # print(geocode_result)
        my_location = geocode_result[0]
        
        self.ui.labelCity.setText("Address: "+ my_location['formatted_address'])
        self.ui.labelLatitude.setText("Latitude(위도): " + str(my_location['geometry']['location']['lat']))        
        self.ui.labelLongitude.setText("Longitude(경도): "+ str(my_location['geometry']['location']['lng']))

if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

 

Getting complete information from latitude and longitude values

In this recipe, you will learn how to find out the complete details of a location whose longitude and latitude values you know. This process of converting a point location, that is, latitude and longitude values, into a readable address (the place name, city, country name, and so on) is known as reverse geocoding.
The application will prompt you to enter longitude and latitude values, and then it will display the matching location name, city, country, and postal code for that location.

demoGoogleMap2.py
0.00MB
demoGoogleMap2.ui
0.00MB

 

 

 

import sys
from PyQt5.QtWidgets import QDialog, QApplication
import googlemaps
from demoGoogleMap2 import *
class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButtonSearch.clicked.connect(self.displayDetails)
        self.show()
        
    def displayDetails(self):
        la = self.ui.lineEditLongitude.text()
        lo = self.ui.lineEditLatitude.text()
        
        gmaps = googlemaps.Client(key='AIzaSyC1lNKXkci393EZ1TcD-C9kQWrEUBKNuJI')
        geocode_result = gmaps.reverse_geocode((la, lo))
        print(geocode_result)
        my_location = geocode_result[0]
        
        self.ui.label_address.setText("Address: "+ my_location['formatted_address'])


if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

Finding out the distance between two locations (수정 필요)

In this recipe, you will learn how to find out the distance in kilometers between the two locations entered by the user. The recipe will simply prompt the user to enter two locations, followed by clicking the Find Distance button, and the distance between the two will be displayed.

 

How to do it…

Let's create an application based on the Dialog without Buttons template by performing the following steps:

  1. Add four QLabel, two QLineEdit, and a QPushButton widget to the form by dragging and dropping four Label, two Line Edit, and a Push Button widget onto the form.
  2. Set the text property of the first Label widget to Find out the distance between two locations, that of the second Label widget to Enter first location, and that of the third Label widget to Enter second location.
  3. Delete the text property of the fourth Label widget because its text property will be set through code; that is, the distance between the two entered locations will be computed through code and displayed in the fourth Label widget.
  4. Set the text property of the Push Button widget to Find Distance.
  5. Set the objectName properties of the two Line Edit widgets to lineEditFirstLocation and lineEditSecondLocation.
  6. Set the objectName property of the Push Button widget to pushButtonFindDistance.
  7. Set the objectName property of the fourth Label widget to labelDistance.
  8. Save the application by name as demoGoogleMap3.ui. The form will now appear as shown in the following screenshot:

The user interface created with Qt Designer is stored in a .ui file and it is an XML file. The XML file is converted into Python code by applying the pyuic5 utility. You can find the generated Python code, demoGoogleMap3.py, in the source code bundle for the book.

  1. To use the GUI created in the demoGoogleMap3.py file, we need to create another Python script and import demoGoogleMap3.py file in that script.
  2. Create another Python file with the name callGoogleMap3.pyw and import the demoGoogleMap3.py code into it:

How it works…

You create an instance of the Client class and name it gmaps. While creating the Client instance, you need to pass the API key that you got on registering with Google. The click() event of the push button with objectName, pushButtonFindDistance, is connected to the displayDistance method. This means that, whenever the push button is clicked, the displayDistance method will be invoked. In the displayDistance method, you invoke the distance_matrix method, passing the Client instance and the two locations entered by the user, to find out the distance between them. The distance_matrix method returns a multidimensional array that is assigned to the data array. From the data array, the distance between the two locations is accessed and assigned to the distance variable. The value in the distance variable is finally displayed through the Label widget.

On running the application, you will be prompted to enter the two locations whose intervening distance you want to know. After entering the two locations, when you click the Find Distance button, the distance between the two locations will be displayed on the screen, as shown in the following screenshot:

 

Displaying location on Google Maps

In this recipe, you will learn how to display a location on Google Maps if you know the longitude and latitude values of that location. You will be prompted to simply enter longitude and latitude values and, when you click the Show Map button, that location will appear on Google Maps.

 

showGoogleMap.py
0.00MB
showGoogleMap.ui
0.00MB

 

 

 

How to do it…

Let's create an application based on the Dialog without Buttons template by performing the following steps:

  1. Add two QLabel, two QLineEdit, a QPushButton, and a QWidget widget to the form by dragging and dropping two Label, two Line Edit, a Push Button, and a Widget container onto the form.
  2. Set the text property of the two Label widgets to Longitude and Latitude.
  3. Set the text property of the Push Button widget to Show Map.
  4. Set the objectName property of the two Line Edit widgets to lineEditLongitude and lineEditLatitude.
  5. Set the objectName property of the Push Button widget to pushButtonShowMap.
  6. Save the application by name as showGoogleMap.ui. The form will now appear as shown in the following screenshot:

  1. Add QWebEngineView, and Set the objectName property of the QWebEngineView widgets to webEngineView.
  1. The user interface created with Qt Designer is stored in a .ui file, which is an XML file and needs to be converted into Python code. The pyuic5 utility is used to convert the XML file into Python code. The generated Python script, showGoogleMap.py, can be seen in the source code bundle for the book.
  2. Treat the showGoogleMap.py script as a header file, and import it into the file from which you will invoke its user interface design.
  3. Create another Python file with the name callGoogleMap.pyw and import the showGoogleMap.py code into it:
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtWebEngineWidgets import QWebEngineView
import googlemaps
from showGoogleMap import *
class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButtonShowMap.clicked.connect(self.dispSite)
        self.show()
    def dispSite(self):
        lng = float(self.ui.lineEditLongitude.text())
        lat = float(self.ui.lineEditLatitude.text())
        URL="https://www.google.com/maps/@" + self.ui.lineEditLatitude.text()+"," + \
            self.ui.lineEditLongitude.text() + ",9z"
        self.ui.webEngineView.load(QUrl(URL))
if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    w.show()
    sys.exit(app.exec_())

 

'Qt5 Python GUI Programming Cookbook' 카테고리의 다른 글

Understanding Layouts  (0) 2023.03.01
Running Python Scripts on Android and iOS  (0) 2023.02.28
Implementing Animation  (0) 2023.02.28
Using Graphics  (0) 2023.02.28
Database Handling  (0) 2023.02.28

댓글