腾讯位置服务的API计算最佳路线(Web)

腾讯位置服务API接口:
https://lbs.qq.com/service/webService/webServiceGuide/webServiceRoute

有的同学可能不太理解:为什么不在Web页面上用JavaScript直接调用腾讯位置服务的API计算最佳路线?其实你这么做也是可以的,但是多了一个隐患:调用腾讯位置服务必须用到密钥。你把密钥写到JS代码中,普通用户查看网页源码就能看到,拿到你的密钥之后,任何人都可以使用这个密钥调用位置服务的API接口,产生的费用由你承担,你觉得合理吗?但是在后端封装就没这个问题。

image

时序图:
image

@Service
@Slf4j
public class MapServiceImpl implements MapService {

    //规划行进路线的API地址
    private String directionUrl = "https://apis.map.qq.com/ws/direction/v1/driving/";
    
    ……

    public HashMap calculateDriveLine(String startPlaceLatitude, 
                                      String startPlaceLongitude,
                                      String endPlaceLatitude, 
                                      String endPlaceLongitude) {
        HttpRequest req = new HttpRequest(directionUrl);
        req.form("from", startPlaceLatitude + "," + startPlaceLongitude);
        req.form("to", endPlaceLatitude + "," + endPlaceLongitude);
        req.form("key", key);

        HttpResponse resp = req.execute();
        JSONObject json = JSONUtil.parseObj(resp.body());
        int status = json.getInt("status");
        if (status != 0) {
            throw new HxdsException("执行异常");
        }
        JSONObject result = json.getJSONObject("result");
        HashMap map = result.toBean(HashMap.class);
        return map;
    }
}
posted @ 2026-01-12 09:00  hwq1992  阅读(0)  评论(0)    收藏  举报