Preface: This article is compiled based on the author's experience with internet mapping services. While consumer map applications offer automatic location detection, professional GIS tools like QGIS lack this functionality natively. This guide demonstrates how to implement this feature.
Implementation Principle
Device positioning typically follows two technical approaches:
- Using GPS hardware to obtain latitude/longitude coordinates
- IP-based geolocation
This article focuses on IP-based positioning. For background on IP geolocation methods, refer to these resources:
- Using IP Addresses to Locate Users
- Advanced IP Geolocation with ip2region
- Positioning Fundamentals: From Oil Discovery to Modern Techniques
QGIS Python API Implementation
The implementation involves three key steps:
- Retrieve the user's public IP address
- Obtain geographic coordinates associated with the IP
- Display the location on the map and adjust the view
Implementation code:
from qgis.PyQt.QtWidgets import QMessageBox
from qgis.core import QgsProject, QgsVectorLayer, QgsFeature, QgsGeometry, QgsPointXY
import requests
def locate_by_ip():
try:
# Get current IP address
ip_response = requests.get('https://api.ipify.org?format=json', timeout=5)
ip_address = ip_response.json()['ip']
# Get geographic coordinates from IP
geo_response = requests.get(f'http://ip-api.com/json/{ip_address}')
geo_data = geo_response.json()
if geo_data['status'] == 'success':
lat = geo_data['lat']
lon = geo_data['lon']
city = geo_data['city']
country = geo_data['country']
# Create temporary layer
layer_name = f"IP_Location_{ip_address}"
layer = QgsVectorLayer("Point?crs=EPSG:4326", layer_name, "memory")
provider = layer.dataProvider()
# Create point feature
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat)))
provider.addFeature(feature)
# Add to map
QgsProject.instance().addMapLayer(layer)
# Center map view
canvas = iface.mapCanvas()
canvas.setCenter(QgsPointXY(lon, lat))
canvas.zoomScale(100000) # Appropriate zoom level
# Display information
QMessageBox.information(iface.mainWindow(), "Location Positioning",
f"IP Address: {ip_address}\n"
f"Location: {city}, {country}\n"
f"Coordinates: {lat:.4f}, {lon:.4f}")
else:
QMessageBox.warning(iface.mainWindow(), "Error", "Failed to retrieve location data")
except Exception as e:
QMessageBox.critical(iface.mainWindow(), "Error", f"Operation failed: {str(e)}")
# Execute function
locate_by_ip()
Usage Instructions
- Open QGIS Python Console
- Create new editor window
- Paste the provided code
- Execute the script
Result demonstration:
Conclusion
The current implementation demonstrates basic IP-based positioning functionality. Note that the test result shows a location in the USA due to limitations in freely available IP geolocation APIs for Chinese regions. Future enhancements will include:
1.Integration with domestic IP geolocation services
2.Implementation of GPS-based positioning solutions
3.Accuracy improvements for regional positioning