随笔 - 754  文章 - 0 评论 - 33 阅读 - 135万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

一、在高德开发平台中注册账号并申请Key

具体操作参照如下:https://lbs.amap.com/api/javascript-api/guide/abc/prepare

注意:服务平台选web服务。因为高德使用手册上写的很清楚:手册

浏览器访问:http://restapi.amap.com/v3/geocode/geo?key=d2abc8eb849******c4e159714e239b&address=洪山区,结果如下:

{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"湖北省武汉市洪山区",
"country":"中国","province":"湖北省","citycode":"027","city":"武汉市","district":"洪山区","township":[],
"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"420111","street":[],
"number":[],"location":"114.343913,30.500317","level":"区县"}]}

二、后台调用

代码如下:

复制代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class GetLonLatTest {
    @Resource
    private AreasMapper areasMapper;

    @Test
    public void test() {
        List<Map> districts = areasMapper.selectAllDistrict();
        districts.stream().forEach(map -> {
            String city = (String) map.get("city");
            int id = Integer.parseInt(String.valueOf(map.get("id")));
            HttpURLConnection conn = null;
            String postUrl = "http://restapi.amap.com/v3/geocode/geo?key=d2abc8eb84********c4e159714e239b&address=" + city;

            String result = null;
            try {
                URL my_url = new URL(postUrl);
                //得到connection对象。
                conn = (HttpURLConnection) my_url.openConnection();
                //允许写出
                conn.setDoOutput(true);
                //允许读入
                conn.setDoInput(true);
                //设置请求方式
                conn.setRequestMethod("GET");
                conn.setUseCaches(false);
                conn.setConnectTimeout(10 * 60 * 1000);
                conn.setReadTimeout(10 * 60 * 1000);
                //设置请求头
                conn.setRequestProperty("Charsert", "UTF-8");
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
                conn.setRequestProperty("Connection", "Keep-Alive");

                //连接网络。请求行,请求头的设置必须放在网络连接前
                conn.connect();

                if (conn.getResponseCode() == 200) {
                    //通过io流得到返回的数据
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String read = null;
                    while ((read = br.readLine()) != null) {
                        sb.append(read);
                        sb.append("\n");
                    }
                    br.close();
                    try {
                        JSONObject respJson = JSONObject.parseObject(sb.toString());
                        JSONArray geocodes = respJson.getJSONArray("geocodes");
                        int size = geocodes.size();
                        for (int i = 0; i < size; i++) {
                            JSONObject jsonObject = geocodes.getJSONObject(i);
                            String location = jsonObject.getString("location");
                            String[] split = location.split(",");
                            String lon = split[0];
                            String lat = split[1];
                            System.out.println("经度:" + lon);
                            System.out.println("纬度:" + lat);
                            // 根据主键id修改sys_areas表的经度和纬度
                            Areas areas = new Areas();
                            areas.setId(id);
                            areas.setLongitude(lon);
                            areas.setLatitude(lat);
                            areasMapper.updateByPrimaryKeySelective(areas);
                        }

                        System.out.println(respJson);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
复制代码

三、vue中使用

1、引入jQuery

1)、安装jquery

cnpm i jquery -s

2)、main.js中引入

import $ from 'jquery'
window.jQuery = $;
window.$ = $;

3)、调用高德API

复制代码
<template>
  <div>
    <div>
      【经纬度】{{location}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  created() {
    this.getLocation()
  },
  data(){
    return{
      location: null
    }
  },
  methods: {// 根据地址获取经纬度
    getLocation () {
      let that = this
      let data = {
        key: 'd2abc8eb8*******e159714e239b',
        address: '洪山区'
      }
      $.ajax({
        url: 'http://restapi.amap.com/v3/geocode/geo',
        type: 'get',
        dataType: 'jsonp',
        data,
        success: function (data) {
          console.log(data.geocodes[0].location)//获取到的经纬度
          that.location = data.geocodes[0].location
        }
      })
    }
  }
}
</script>
复制代码

效果如下:

注意:调用高德API需要在外网环境,如果是内网,则无法使用。



感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接
posted on   周文豪  阅读(3146)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示