Java实现高德地图地理围栏设置功能工具类

前两天做项目需要用到高德地图的地理围栏功能,想从网上找一下教程,看见全是前端或者php的教程没有Java的教程,这边研究了一下特地写了一个工具类来实现。

准备工作
需要导入HttpClient的Jar包来实现http请求,这边就不放jar包了,网上搜HttpClient maven是可以搜到的。

 加端端老师免费领取更多编程资料

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
 
/**
 * @Description 高德电子围栏工具类
 * [url=home.php?mod=space&uid=686208]@AuThor[/url] Veddy
 * [url=home.php?mod=space&uid=686237]@date[/url] 2020-07-10
 */
public class AMapFenceUtils {
 
    /**
     * 高德地图地理围栏创建
     * [url=home.php?mod=space&uid=952169]@Param[/url] key 高德地图Web服务API类型Key
     * @param name 围栏名称
     * @param points 电子围栏经纬度 例"117.317159,31.852989;117.297525,31.847862;117.296071,31.86483"
     * @param desc 电子围栏描述
     * @return
     */
    public static String createFence(String key,String name,String points,String desc){
 
        //组装url
        String url = "https://restapi.amap.com/v4/geofence/meta?key=" + key;
 
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post请求方式实例
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头 发送的是json数据格式
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Close");
 
        JSONObject jsonObject = new JSONObject();
        //围栏名称
        jsonObject.put("name",name);
        //围栏经纬度
        jsonObject.put("points",points);
        //电子围栏有效期
        jsonObject.put("valid_time","2050-12-30");
        //电子围栏监控频率
        jsonObject.put("repeat","Mon,Tues,Wed,Thur,Fri,Sat,Sun");
        //备注
        if (desc != null){
            jsonObject.put("desc",desc);
        }
 
        // 设置参数---设置消息实体 也就是携带的数据
        StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
        // 设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        // 把请求消息实体塞进去
        httpPost.setEntity(entity);
 
        // 执行http的post请求
        CloseableHttpResponse httpResponse;
        String result = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return result;
    }
 
    /**
     * 更新电子围栏的经纬度
     * @param key 高德地图Web服务API类型key
     * @param gid 围栏全局ID 创建围栏后返回
     * @param name 围栏名称
     * @param points 电子围栏经纬度 例"117.317159,31.852989;117.297525,31.847862;117.296071,31.86483"
     * @return
     */
    public static String updateFence(String key,String gid,String name,String points){
 
        //组装URL
        String url = "https://restapi.amap.com/v4/geofence/meta?key="+ key +"&gid=" + gid;
 
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post请求方式实例
//        HttpPost httpPost = new HttpPost(url);
        HttpPatch httpPatch = new HttpPatch(url);
        // 设置请求头 发送的是json数据格式
        httpPatch.setHeader("Content-type", "application/json;charset=utf-8");
        httpPatch.setHeader("Connection", "Close");
 
        JSONObject jsonObject = new JSONObject();
        //围栏名称
        jsonObject.put("name",name);
        //围栏经纬度数组
        jsonObject.put("points",points);
        //电子围栏有效期
        jsonObject.put("valid_time","2050-12-30");
        //电子围栏监控频率
        jsonObject.put("repeat","Mon,Tues,Wed,Thur,Fri,Sat,Sun");
 
        // 设置参数---设置消息实体 也就是携带的数据
        StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
        // 设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        // 把请求消息实体塞进去
        httpPatch.setEntity(entity);
 
        // 执行http的post请求
        CloseableHttpResponse httpResponse;
        String result = null;
        try {
            httpResponse = httpClient.execute(httpPatch);
            result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return result;
 
    }
 
    /**
     * 验证是否在电子围栏内部
     * @param key 高德地图Web服务Api类型Key
     * @param diu 设备唯一标识
     * @param locations 设备经纬度
     * @return
     */
    public static String checkFence(String key,String diu,String locations){
 
        //获取unix时间戳
        String dateStr = Long.toString(System.currentTimeMillis()/1000L);
        String url = "https://restapi.amap.com/v4/geofence/status?key="+ key +"&diu="+ diu +"&locations=" + locations+","+dateStr;
 
        String result = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
    /**
     * 删除地理围栏
     * @param key 高德地图Web服务Api类型Key
     * @param gid 地理围栏全局ID 创建围栏后返回
     * @return
     */
    public static String deleteFence(String key,String gid){
 
        //组装URL
        String url = "https://restapi.amap.com/v4/geofence/meta?key="+ key +"&gid=" + gid;
 
        String result = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http DELETE请求
            HttpDelete httpDelete = new HttpDelete(uri);
            // 执行请求
            response = httpclient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
}

好的,我了解了您的问题。实现高德地图地理围栏设置功能需要使用高德地图的API和Java编程语言。下面是一个简单的Java工具类,可以帮助您实现电子围栏设置: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class GeoFenceTool { private static final String KEY = "您的高德地图API密钥"; // 高德地图API密钥 /** * 创建电子围栏 * * @param name 电子围栏名称 * @param points 电子围栏坐标点(多边形) * @return 返回电子围栏ID */ public static String createGeoFence(String name, String points) { String url = "https://restapi.amap.com/v4/geofence/meta?key=" + KEY; String param = "{\"name\":\"" + name + "\",\"points\":\"" + points + "\"}"; String result = sendPost(url, param); String geofenceId = result.substring(result.indexOf("gid\":\"") + 6, result.indexOf("\",\"name\"")); return geofenceId; } /** * 删除电子围栏 * * @param geofenceId 电子围栏ID * @return 返回删除结果 */ public static String deleteGeoFence(String geofenceId) { String url = "https://restapi.amap.com/v4/geofence/meta/" + geofenceId + "?key=" + KEY; String result = sendDelete(url); return result; } /** * 发送POST请求 * * @param url 请求地址 * @param param 请求参数 * @return 返回请求结果 */ private static String sendPost(String url, String param) { StringBuilder result = new StringBuilder(); BufferedReader in = null; HttpURLConnection conn = null; try { URL realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.getOutputStream().write(param.getBytes()); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } if (conn != null) { conn.disconnect(); } } return result.toString(); } /** * 发送DELETE请求 * * @param url 请求地址 * @return 返回请求结果 */ private static String sendDelete(String url) { StringBuilder result = new StringBuilder(); BufferedReader in = null; HttpURLConnection conn = null; try { URL realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("DELETE"); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } if (conn != null) { conn.disconnect(); } } return result.toString(); } } ``` 使用方法: 1. 在高德地图开放平台上申请API密钥,并将其替换到KEY变量中。 2. 调用createGeoFence方法创建电子围栏,传入电子围栏名称和坐标点参数。坐标点格式为:经度,纬度;经度,纬度;经度,纬度...(多边形)。 3. 如果需要删除电子围栏,调用deleteGeoFence方法并传入电子围栏ID参数。 注意:本工具类仅供参考,具体实现需要根据项目需求进行调整。同时,使用高德地图API时请遵守《高德地图开放平台服务协议》等相关法律法规。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值