腾讯地图api获取地理位置、经纬度等信息

需要使用地图搜索,并点击结果后去省市区、经纬度、详细地址、行政区信息

var citylocation; // 定位当前城市
        var searchService; // 地图搜索
        var geocoder; // 地址解析
        var map; // 地图
        var markers = new Array(); // 搜索结果
        var init = function() {
            var center = new qq.maps.LatLng(39.916527, 116.397128);
            map = new qq.maps.Map(document.getElementById('mapcontainer'), {
                center: center,
                zoom: 13
            });
            //设置城市信息查询服务
            citylocation = new qq.maps.CityService({
                //请求成功回调函数
                complete: function(result) {
                    console.log(result)
                    map.setCenter(result.detail.latLng);
                    //alert(result.detail.latLng);
                },
                error: function() {
                    alert("出错了,请输入正确的经纬度!!!");
                }
            });
            citylocation.searchLocalCity();

            geocoder = new qq.maps.Geocoder();
            geocoder.setComplete(function(result) {
                console.log(result)
                map.setCenter(result.detail.location);
                var info = new qq.maps.InfoWindow({
                    map: map
                });
                info.open();
                info.setContent('<div style="width:280px;height:50px;">' +
                    result.detail.address + '</div>');
                info.setPosition(result.detail.location);
                document.getElementById("province").value = result.detail.addressComponents.province;
                document.getElementById("city").value = result.detail.addressComponents.city;
                document.getElementById("distric").value = result.detail.addressComponents.district;
                document.getElementById("lng").value = result.detail.location.lng;
                document.getElementById("lat").value = result.detail.location.lat;
                document.getElementById("address").value = result.detail.address;

                if (result.detail.addressComponents.district != '') {
                    var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
                    httpRequest.open('POST', '/api/area/map-search', true); //第二步:打开连接
                    httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
                    httpRequest.send('keyword='+result.detail.addressComponents.district);//发送请求 将情头体写在send中
                    /**
                     * 获取数据后的处理程序
                     */
                    httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
                        if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
                            var pointInfo = JSON.parse(httpRequest.responseText);//获取到服务端返回的数据
                            if (pointInfo.code == 200) {
                                document.getElementById("code").value = pointInfo.data.code;
                            }
                        }
                    };
                }

            });

            searchService = new qq.maps.SearchService({
                //检索成功的回调函数
                complete: function(results) {
                    //设置回调函数参数
                    var pois = results.detail.pois;
                    /*var info = new qq.maps.InfoWindow({
                        map: map
                    });*/
                    var latlngBounds = new qq.maps.LatLngBounds();
                    for (var i = 0, l = pois.length; i < l; i++) {
                        var poi = pois[i];
                        //扩展边界范围,用来包含搜索到的Poi点
                        latlngBounds.extend(poi.latLng);

                        (function(n) {
                            var marker = new qq.maps.Marker({
                                map: map
                            });
                            marker.setPosition(pois[n].latLng);

                            marker.setTitle(i + 1);
                            markers.push(marker);

                            qq.maps.event.addListener(marker, 'click', function() {
                                //infoWin.open();
                                //infoWin.setContent('<div style="width:280px;height:100px;">' + 'POI的ID为:' +
                                //    pois[n].id + ',POI的名称为:' + pois[n].name + ',POI的地址为:' + pois[n].address + ',POI的类型为:' + pois[n].type + '</div>');
                                //infoWin.setPosition(pois[n].latLng);

                                //infoWin.setPosition(pois[n].latLng);
                                geocoder.getAddress(pois[n].latLng);
                            });
                        })(i);
                    }
                    //调整地图视野
                    map.fitBounds(latlngBounds);
                },
                //若服务请求失败,则运行以下函数
                error: function(e) {
                    console.log(e)
                    alert("出错了。");
                }
            });

            function clearOverlays(overlays) {
                var overlay;
                while (overlay = overlays.pop()) {
                    overlay.setMap(null);
                }
            }

            document.getElementById("searchmapBtn").addEventListener("click", function (ev) {
                var keyword = document.getElementById("searchmap").value;
                var pageIndex = 0;
                var pageCapacity = 5;

                clearOverlays(markers);
                //设置搜索页码
                searchService.setPageIndex(pageIndex);
                //设置每页的结果数
                searchService.setPageCapacity(pageCapacity);
                //根据输入的关键字在搜索范围内检索
                searchService.search(keyword);
            })
        }

        window.onload = init;

 

获取行政区因为跨域问题,需要在后台通过get获取

public Map<String, String> getInfoByKeyword(String keyword)
    {
        String url = "https://apis.map.qq.com/ws/district/v1/search?&keyword="+keyword+"&key="+mapkey;
        JSONObject res = HttpTools.doHttpGet(url);

        Map<String, String> result = new HashMap<String, String>();
        if (null != res) {
            try {
                Integer status = res.getInt("status");

                if (status == 0) {
                    JSONArray areas = res.getJSONArray("result");
                    if (areas.length() > 0) {
                        JSONArray first = areas.getJSONArray(0);
                        // 可能返回多个,只获取第一个
                        JSONObject info = first.getJSONObject(0);
                        String lat = "";
                        String lng = "";
                        if (info.has("location")) {
                            JSONObject location = info.getJSONObject("location");
                            lat = location.getString("lat");
                            lng = location.getString("lng");
                        }
                        String code = info.getString("id");
                        String name = info.getString("fullname");

                        result.put("code", code);
                        result.put("name", name);
                        result.put("lat", lat);
                        result.put("lng", lng);
                        return result;
                    }
                }
                result.put("msg", "没有相关数据");
            } catch (JSONException ex) {
                result.put("msg", "解析数据失败");
            }
        }
        result.put("msg", "获取数据失败");
        return result;
    }

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在web端使用腾讯地图API获取用户地理位置,可以使用HTML5中的Geolocation API。以下是一些简单的步骤: 1. 注册腾讯地图开发者账号并创建应用程序,然后获取密钥。 2. 在HTML页面中嵌入JavaScript代码,使用Geolocation API请求用户位置: ```javascript if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { alert("Geolocation is not supported by this browser."); } function showPosition(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; // 调用腾讯地图API进行地理编码 } ``` 3. 在showPosition函数中,可以将用户的经纬度坐标传递给腾讯地图API进行地理编码,以获取用户位置的详细信息: ```javascript function showPosition(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; var url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=YOUR_KEY"; fetch(url) .then(response => response.json()) .then(data => { console.log(data.result.formatted_addresses.recommend); // 显示用户位置信息 }); } ``` 在以上代码中,需要将YOUR_KEY替换为你在腾讯地图开发者账号中生成的API密钥。 4. 最后,可以将获取到的用户位置信息显示在页面上,以便用户查看。 需要注意的是,使用Geolocation API获取用户位置需要用户授权。在请求用户授权时,可以使用下面的代码: ```javascript navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { navigator.geolocation.getCurrentPosition(showPosition); } else if (result.state === 'prompt') { navigator.geolocation.getCurrentPosition(showPosition, showError); } else if (result.state === 'denied') { showError("User denied geolocation"); } }); ``` 在以上代码中,使用permissions.query()函数查询用户是否授权Geolocation API,并根据结果调用相应的函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值