百度地图定位Demo

//获取定位城市
    @RequestMapping(value = "/cityName.html", method = { RequestMethod.POST })
    public @ResponseBody HttpJsonResult<String> getLoginUser(HttpServletRequest request,
            HttpServletResponse response) {

        //获取定位城市
        String longitude = request.getParameter("longitude");
        String latitude = request.getParameter("latitude");
        String jwd = latitude+","+longitude;
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        paramList.add(new BasicNameValuePair("ak", "你的百度AK"));//传递的参数
        paramList.add(new BasicNameValuePair("sn", ""));//传递的参数
        paramList.add(new BasicNameValuePair("output", "json"));//传递的参数
        paramList.add(new BasicNameValuePair("pois", "1"));//传递的参数
        paramList.add(new BasicNameValuePair("location", jwd));//传递的参数
        String urlString = "http://api.map.baidu.com/geocoder/v2/";
        String entity = HttpClientUtil.post(urlString, paramList);
        Map<String,Object> resultMap = JsonUtil.fromJson(entity);
        Map<String,Object> m = (Map) resultMap.get("result");
        Map<String,String> add = (Map<String, String>) m.get("addressComponent");
        String city = add.get("city");
        city = city.replace("市","");
        HttpJsonResult<String> jsonResult = new HttpJsonResult<String>();
        jsonResult.setData(city);
        return jsonResult;
    }

json工具

   /**
     * 将JSON字符串反序列化为Java对象。
     * @param json JSON字符串
     * @return
     * <li>json字符串为空时返回null;
     * <li>json字符串为无效JSON格式时,会记录日志,返回null;
     */
    public static final <T> T fromJson(String json) {
        if (StringUtil.isEmpty(json))
            return null;

        try {
            Type type = new TypeToken<T>() {
            }.getType();
            Gson gson = new Gson();
            return gson.fromJson(json, type);
        } catch (Exception e) {
            log.warn("Invalidate json format:" + json, e);
            return null;
        }
    }

Http请求工具类

public static String post(String url, List<? extends NameValuePair> parameters) {
		return post(url, parameters, DEFAULT_CHARSET);
	}

	public static String post(String url, String parameters) {
		return post(url, parameters, DEFAULT_CHARSET);
	}

	public static String post(String url, List<? extends NameValuePair> parameters, String charset) {
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
		if (parameters != null && parameters.size() > 0) {
			UrlEncodedFormEntity entity;
			try {
				entity = new UrlEncodedFormEntity(parameters, charset);
				httpPost.setEntity(entity);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return sendHttpRequest(httpPost, charset);
	}

前端js

 //定位
    var longitude =  '';
    var latitude = '';
    var options={
        enableHighAccuracy:true, //boolean 是否要求高精度的地理信息
        timeout:0,//表示等待响应的最大时间,默认是0毫秒,表示无穷时间
        maximumAge:1000//应用程序的缓存时间
    }
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(onSuccess,onError,options );
    function onSuccess(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            //创建地图实例
            var map =new BMap.Map("container");
            // 经度+经度校正值: 0.01863369751900734
            //   纬度+纬度校正值: -0.004080683120882611;
            longitude =  r.point.lng+0.01863369751900734;
            latitude =  r.point.lat-0.004080683120882611;

            $.ajax({
                type: "POST",
                url: "${(domainUrlUtil.EJS_URL_RESOURCES)!}/h5/cityName.html",
                data: {longitude:longitude,latitude:latitude},
                success: function (data) {
                    //加载数据
                    var cityName1 =  $("#cityName1").val();

                    //切换城市
                    if(cityName1 != ""){
                        $("#cityName").html(cityName1);
                        localStorage.setItem("cityName",cityName1);
                    }else {//第一次定位
                        if(localStorage.getItem("cityName") == null || localStorage.getItem("cityName") == ""){
                            $("#cityName").html(data.data);
                            localStorage.setItem("cityName",data.data);
                        }else {//已经定位过
                            $("#cityName").html(localStorage.getItem("cityName"));
                        }
                    }
               
                }
            });
        } else {
        }
    };

使用百度API的正逆地理编码。做为参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值