Pyqt custom static map application

Source: Internet
Author: User
Tags qt designer netbeans

Custom static map applications

Next we will create a new Python project in the python ide of netbeans, and click Create project, as shown in page 3-9.

 
(Click to view the big picture) fig 33-9 create a python Project

Enter the project name staticmap. Python ide will create a code file named staticmap. py for us and set it as the main file, as shown in 33-10.

 
(Click to view the big picture) Figure 33-10 to set the project name and storage location

The following code is added for the generated main file staticmap. py. First, load the required module at the beginning of the program. The reference part of the code segment is as follows:

from PyQt4.QtCore import * 
from PyQt4.QtGui import *
import urllib

Introduce the classes included in qtcore and qtgui. The basic modules of pyqt4 are included in qtgui. Because the request for a static map still needs to parse the URL address, the urllib class library is introduced to process the http-related part.

The main program is not complex, and its code is as follows:

def main(): 
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())

For the pyqt4 program, you need to create an application object. The application class is located in the qtgui module, and the main body of the program is the qapplication. SYS. argv is used to input command line parameters.

Mywindow is a class used to define the form. W. Show () is used to display the defined form. Finally, the main program enters the Application Event loop. The events to be processed are received repeatedly from the window, and then distributed to the corresponding event processing method.

To terminate an event loop, you must call the exit () method or destroy the widget. Calling the SYS. Exit () method ensures that the program exits correctly and notifies the system when exiting. Because exec is a keyword of Python, there is an underscore after the exec _ () method to indicate the difference with the keyword.

In the mywindow class, we specify that the qdialog is the ui_dialog generated by the UI file in the QT designer (must be consistent with the name specified in the uidesigner). The Code is as follows:

class MyWindow(QDialog): 
def __init__(self, *args):
QDialog.__init__(self, *args)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
# create connection
self.connect(self.ui.pushButton, SIGNAL("clicked()"), self.run_command)

The code segment in _ init _ customizes the appearance of the interface. We reference the ui_dialog generated by UI file compilation in the QT designer. Of course, if the interface is not very complex, you can manually write the function to add the text box, buttons, and other components to be displayed in the form.

Here, we use the signal slot mechanism to connect the confirmation button with the next command execution operation run_command. That is to say, when the button is clicked, The triggered event is handled by the run_command function.
The code snippet of the run_command function is as follows:

def run_command(self):
addr = str(self.ui.le.text().toUtf8())
self.getGeoCode(addr)

Obtain the address obtained from the input column in the function as the query condition and pass it to the getgeocode function, qlineedit. the qstring returned by text () is different from the python string. It can be converted to a unicode string and then assigned to the string variable.

The code segment for the getgeocode function to obtain coordinates is as follows:

def getGeoCode(self, addr):
geo_url='http://maps.google.com/maps/geo?'+urllib.urlencode
({'q':addr})+'&output=csv&key='+google_key
try:
g=urllib.urlopen(geo_url)
ret=g.read().split(',')          
if(ret[0]!='200'):
       QMessageBox.warning(None, "Error", addr+" not found", QMessageBox.Yes)
else:
       self.showMap(ret[2], ret[3])  
except urllib.HTTPError:
QMessageBox.warning(None, "Error", "Http error", QMessageBox.Yes)

In a static map request, the input item is the place name of the requested address. You must use the address decoding function provided by Google to convert the location of the place name to the longitude and latitude. Therefore, the URL string we use is "http://maps.google.com/maps/Geo? "The following parameters are the query address, and output is the output format. Currently, the output formats include XML, kml, CSV, and JSON. Here, the CSV format is separated by commas, add the previously applied Google Maps API key to get the resolved address coordinates.

With the support of the urllib library, we get the address coordinates of the Request Location. If the coordinates corresponding to the address are not found, a message is displayed using qmessagebox to prompt the user. If the coordinates corresponding to the address are found, the longitude and latitude coordinates are passed as parameters to the showmap function to display the corresponding map.

The code snippet of the showmap function is as follows:

def showMap(self, lat,lang): 
stmap_url='http://maps.google.com/staticmap?center=
'+lat+','+lang+'&markers='+lat+','+lang+',red&zoom=
14&size=512x512&maptype=mobile&key='+google_key
urllib.urlretrieve(stmap_url, "stmap.gif")
image = QImage("stmap.gif")
self.ui.imageLabel.setPixmap(QPixmap.fromImage(image))
self.ui.imageLabel.adjustSize()

After obtaining the coordinates correctly, we pass the latitude (LAT) and longitude (Lang) to the showmap function to assemble the string requesting the static map. The scale level defined here is 14. In Google maps, the scaling range is 0 ~ Level 18 is the whole earth, and level 18 is the most precise map. However, in addition to the United States, Canada and other countries, it is often impossible to obtain the most detailed map.

The retrieved map size is set to 512 pixels × 512 pixels, and 512 pixels × 512 pixels are the largest images available. The maptype type is set to Mobile, which is suitable for viewing on portable devices. You can also place custom icons on the map. In this example, the default icon is displayed in the image center.

The obtained static map uses urllib.urlretrieve(picture watermark to save it as an image named stmap.gif, and then fills the image in the display label corresponding to imagelabel. In this way, the obtained map can be displayed in the corresponding window of the program.

Click Run (F6) in netbeans to start the application. In the displayed dialog box, enter Los Angeles for short, "La", and click OK, you can get the map returned by Google static map in the program, as shown in 33-11.

 
(Click to view the big chart) fig 33-11 call Google's static map in the program

The complete application code is as follows:

import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import urllib
from ui_staticmap import Ui_Dialog
google_key='YOU_API_KEY_HERE'
def main(): 
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())

class MyWindow(QDialog):
def __init__(self, *args):
QDialog.__init__(self, *args)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
# create connection
self.connect(self.ui.pushButton, SIGNAL("clicked()"), self.run_command)
def getGeoCode(self, addr):
geo_url='http://maps.google.com/maps/geo?'+urllib.urlencode
({'q':addr})+'&output=csv&key='+google_key
try:
g=urllib.urlopen(geo_url)
ret=g.read().split(',')          
if(ret[0]!='200'):
QMessageBox.warning(None, "Error",
addr+" not found", QMessageBox.Yes)
else:
self.showMap(ret[2], ret[3])  
except urllib.HTTPError:
QMessageBox.warning(None, "Error",
"Http error", QMessageBox.Yes)
def showMap(self, lat,lang): 
stmap_url='http://maps.google.com/staticmap?center='+lat+','
+lang+'&markers='+lat+','+lang+',red&zoom=14&size=
512x512&maptype=mobile&key='+google_key
urllib.urlretrieve(stmap_url, "stmap.gif")
image = QImage("stmap.gif")
self.ui.imageLabel.setPixmap(QPixmap.fromImage(image))
self.ui.imageLabel.adjustSize()
    def run_command(self):
addr = str(self.ui.le.text().toUtf8())
self.getGeoCode(addr)

if __name__ == "__main__":
main()

So far, Google's static map function has only played a small part. Interested friends can further expand the program, add the adjustment of the map zoom level and manual position for the application, you can even set the path on a static map.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.