如何正确拼接经纬度生成Google地图URL并通过GSM模块发送?
Problem Description
I wrote the following code to split a response and extract latitude and longitude, then concatenate them into a Google Maps link to send via a GSM module. However, I'm struggling with the string concatenation step. Here's my code:
array = response.split(",") lat=array[3] print lat lon=array[4] print(lon) stringlink="http://maps.google.com/maps?q=loc:" + lat,lon print(stringlink) return(lat,lon)I need to properly combine
latandlonintostringlinkso it can be sent successfully via the GSM module. Can someone help me resolve this?
Solution
Hey there! Let’s get that URL concatenation sorted out for you.
The main issue in your current code is this line:
stringlink="http://maps.google.com/maps?q=loc:" + lat,lon
You’re using a comma instead of properly joining lat and lon with a comma separator (Google Maps expects the format loc:lat,lon in the URL query string). Plus, if you’re using Python 3, print lat will throw a syntax error—you’ll need parentheses around the argument, like print(lat).
Here are a few clean, reliable ways to build your URL correctly:
1. Basic String Concatenation
Use the + operator to join all parts, making sure to add a comma between lat and lon:
stringlink = "http://maps.google.com/maps?q=loc:" + lat + "," + lon
2. F-String Formatting (Python 3.6+)
This is the most readable approach for modern Python versions:
stringlink = f"http://maps.google.com/maps?q=loc:{lat},{lon}"
3. .format() Method (Compatible with Older Python Versions)
If you’re working with Python 2 or early Python 3 versions, use this method:
stringlink = "http://maps.google.com/maps?q=loc:{},{}".format(lat, lon)
4. String Joining
Another clean option is to first join the coordinates, then insert them into the URL:
coordinate_pair = ",".join([lat, lon]) stringlink = f"http://maps.google.com/maps?q=loc:{coordinate_pair}"
A quick check: since response.split(",") returns string values, lat and lon should already be strings—no need to convert them unless you’ve modified them elsewhere.
Once you have the correctly formatted stringlink, you can pass it directly to your GSM module’s transmission function. This URL will open the exact location in Google Maps when accessed, which is perfect for your use case.
内容的提问来源于stack exchange,提问作者Anonymous_hacker

