java腾讯经纬度转高德
时间: 2023-08-08 08:01:39 浏览: 215
使用高德获取经纬度
在Java中,将腾讯经纬度转换为高德经纬度可以使用第三方库进行实现。以下是一个例子:
首先,你需要导入第三方库"org.apache.commons.codec.digest"和"gson",这些库都可以通过Maven或Gradle进行引入。
使用以下代码片段来进行经纬度的转换:
```java
import org.apache.commons.codec.binary.Hex;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class TencentToAmapConverter {
private static final String KEY = "your_amap_key";
private static final String SECRET = "your_amap_secret";
public static void main(String[] args) {
double tencentLng = 113.937255;
double tencentLat = 22.539111;
String location = tencentLng + "," + tencentLat;
String sig = generateSignature(location);
try {
String response = HttpRequest.sendGet("https://restapi.amap.com/v3/assistant/coordinate/convert",
"locations=" + location + "&coordsys=tencent&output=json&key=" + KEY + "&sig=" + sig);
JsonObject convertedLocation = JsonParser.parseString(response)
.getAsJsonObject().get("locations").getAsJsonArray().get(0).getAsJsonObject();
double amapLng = convertedLocation.get("lng").getAsDouble();
double amapLat = convertedLocation.get("lat").getAsDouble();
System.out.println("腾讯经纬度: " + tencentLng + ", " + tencentLat);
System.out.println("高德经纬度: " + amapLng + ", " + amapLat);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String generateSignature(String location) {
String rawData = "/v3/assistant/coordinate/convert?coordsys=tencent&locations=" + location + "&output=json&key="
+ KEY + SECRET;
return sha1Hex(rawData);
}
private static String sha1Hex(String rawData) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] digest = messageDigest.digest(rawData.getBytes(StandardCharsets.UTF_8));
return new String(Hex.encodeHex(digest, false));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
}
class HttpRequest {
public static String sendGet(String url, String params) throws IOException {
// 省略实现细节,可以使用HttpURLConnection或OkHttp等进行发送网络请求
return "";
}
}
```
这段代码将腾讯经纬度转换为高德经纬度,并通过在高德开放平台上申请的key来进行签名,确保安全性。请替换代码中的"your_amap_key"和"your_amap_secret"为你在高德开放平台上获得的key和secret。
阅读全文