




已阅读5页,还剩21页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
地区经纬度信息获取(利用Google地图API获取)package com.leg3s.rld.util;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .URL;import .URLConnection;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.log4j.Logger;/* 地址经纬度信息获取工具类* * author liuw* create date 2010/01/18*/public class AddressLatLngUtilprivate static final String REQUEST_ENCODE = UTF-8;private static final String ADDRESS_KEY = address;private static final String ADDRESS_COUNTRY_KEY = CountryName;private static final String ADDRESS_REGION_KEY = AdministrativeAreaName;private static final String ADDRESS_CITY_KEY = LocalityName;private static final String ADDRESS_POINT_KEY = coordinates;private static final String ADDRESS_SPLIT_STR = :;private static final String LOCATION_COUNTRY_KEY = country;private static final String LOCATION_REGION_KEY = region;private static final String LOCATION_CITY_KEY = city;/private static final String LOCATION_POINT_KEY = location;private static final String LOCATION_POINT_LATITUDE_KEY = latitude;private static final String LOCATION_POINT_LONGITUDE_KEY = longitude;private static final String LOCATION_POINT_PRECISIONY_KEY = accuracy;private static final String LOCATION_SPLIT_STR = ,;public static final int MIN_ZOOM = 11;public static final int MAX_ZOOM = 18;private static final int DOWNNUM_FOR_PROXY = 8000;private static final int CONNECT_TIMEOUT = 30000; / 30秒private static final int THREAD_SLEEP_MILLIS = 200;private static boolean flag = false;private static int downNum = 0;private static String proxyHost = 0;private static String proxyPort = 3128;private static String proxySet = true;private static final Logger logger = Logger.getLogger(AddressLatLngUtil.class);/* 获取地址详细信息及经纬度信息* * param address* return Map*/public static Map getAddressLatLng(String address)StringBuilder urlBuilder = new StringBuilder();urlBuilder.append(/maps/geo);urlBuilder.append(?output=json);urlBuilder.append(&oe=utf-8);urlBuilder.append(&q=).append(encodeURLForUTF8(address);urlBuilder.append(&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA);urlBuilder.append(&mapclient=jsapi);urlBuilder.append(&hl=zh-CN);urlBuilder.append(&callback=_xdc_._1g4gm5mh3);/(urlBuilder.toString();HttpURLConnection httpConnection = null;try/ 1、构造HttpURLConnection连接URL url = new URL(urlBuilder.toString();URLConnection urlConnection = url.openConnection();httpConnection = (HttpURLConnection) urlConnection;httpConnection.setDoInput(true);httpConnection.setDoOutput(true);httpConnection.setConnectTimeout(CONNECT_TIMEOUT);httpConnection.connect();/ 2、接收响应结果InputStream inStream = httpConnection.getInputStream();String htmlContent = getContentByStream(inStream, REQUEST_ENCODE);/ 关闭流资源inStream.close();/ 3、解析结果Map map = parseAddressLatLng(htmlContent); updateProxy();return map; catch (Exception e)/ TODO Auto-generated catch blocke.printStackTrace();logger.error(=获取经纬度信息异常!请求地址: + address, e);return java.util.Collections.emptyMap(); finally/ 关闭连接if (null != httpConnection)httpConnection.disconnect();/* 根据地址信息获取经纬度* * param addressList 地址集合* return ListMap*/public static ListMap getAddressLatLng(List addressList)ListMap list = new ArrayListMap();if (null = addressList | addressList.isEmpty()return list;for (String address : addressList)try/ 休息一下Thread.sleep(THREAD_SLEEP_MILLIS); catch (InterruptedException e)/ TODO Auto-generated catch blocke.printStackTrace();Map addrMap = getAddressLatLng(address);if(false = addrMap.isEmpty()list.add(addrMap);else/System.out.println(address + point is null!);logger.warn(=获取经纬度信息为空!请求地址: + address);return list;/* 解析网页内容地址信息及经纬度信息* * param htmlContent* return Map*/private static Map parseAddressLatLng(String htmlContent)Map addr = new HashMap(1);if (isNullOrEmpty(htmlContent)return addr;String contents = htmlContent.split(rn);String ss = null;String address = null;String country = null;String region = null;String city = null;Point point = null;for (String line : contents)if (isNullOrEmpty(line)continue;line = line.trim();if (line.contains(ADDRESS_POINT_KEY)/* coordinates: 113.9465830, 22.5309650, 0 */ss = line.split(ADDRESS_SPLIT_STR);if (null != ss & ss.length 1)String pointStr = getMiddleStr(ss1, , );String pss = pointStr.split(,);if (null != pss & pss.length 1)double defaultValue = 0D;point = new Point(isNullOrEmpty(pss0)?defaultValue:Double.parseDouble(pss0.trim(), isNullOrEmpty(pss1)?defaultValue:Double.parseDouble(pss1.trim();else if (line.contains(ADDRESS_KEY)address = getValue(line, ADDRESS_KEY);else if (line.contains(ADDRESS_COUNTRY_KEY)country = getValue(line, ADDRESS_COUNTRY_KEY);else if (line.contains(ADDRESS_REGION_KEY)region = getValue(line, ADDRESS_REGION_KEY);else if (line.contains(ADDRESS_CITY_KEY)city = getValue(line, ADDRESS_CITY_KEY);/ 默认取第一个地址信息if (false = isNullOrEmpty(address)& null != point)point.setCountry(country);point.setRegion(region);point.setCity(city);break; / end-for-contents/ 如果地址不为空if (false = isNullOrEmpty(address) addr.put(address, point);return addr;/* 获取中间字符串内容* * param content* param beginStr* param endStr* return*/private static String getMiddleStr(String content, String beginStr, String endStr)String str = ;if (isNullOrEmpty(content)return str;content = content.trim();int bIndex = content.indexOf(beginStr);int eIndex = -1;if (null != beginStr & beginStr.equals(endStr)int index = content.substring(bIndex+beginStr.length().indexOf(endStr);eIndex = content.substring(0, bIndex+beginStr.length().length() + index;else if (null != endStr & false = endStr.equals(beginStr)eIndex = content.indexOf(endStr);if (-1 != bIndex & -1 != eIndex)str = content.substring(bIndex+beginStr.length(), eIndex);return str;private static final String PROXY_HOST_KEY = xyHost;private static final String PROXY_PORT_KEY = xyPort;private static final String PROXY_SET_KEY = xySet;/* 切换代理*/private static synchronized void updateProxy()downNum+;if (downNum % DOWNNUM_FOR_PROXY = 0)if (flag)clearProxy();flag = false;elsesetProxy();flag = true;private static void setProxy()System.setProperty(PROXY_HOST_KEY, proxyHost);System.setProperty(PROXY_PORT_KEY, proxyPort);System.setProperty(PROXY_SET_KEY, proxySet);(setProxy=+proxyHost+:+proxyPort);/System.out.println(setProxy=+proxyHost+:+proxyPort);private static void clearProxy()System.clearProperty(PROXY_HOST_KEY);System.clearProperty(PROXY_PORT_KEY);System.clearProperty(PROXY_SET_KEY);(clearProxy=);/System.out.println(clearProxy=);private static String encodeURLForUTF8(String str)trystr = .URLEncoder.encode(str, UTF-8); catch (UnsupportedEncodingException e)/ TODO Auto-generated catch blocke.printStackTrace();logger.error(字符串转码异常,字符串:+ str, e);return str;/* 按照指定编码从流中读取信息* * param inStream* param encode* return* throws IOException*/private static String getContentByStream(InputStream inStream, String encode) throws IOExceptionif (null = inStream)return null;StringBuilder content = new StringBuilder();/ 采用指定编码格式读取流内容BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encode);String message = null;while (null != (message = reader.readLine()content.append(message);content.append(rn);/ 关闭读取器,释放资源reader.close();return (content.toString();/* 获取偏移后的经纬度(Google中国地图偏移接口) * 中国地图和卫星图都存在偏移量,这个是由中国规划局确定的,* google的地图服务,以ditu.gogle开头的都没有偏差,以maps.google开头的服务就有偏差* * param zoom* 偏移级别(从11级到18级,18级最精确)* param sourcePoint* 经纬度对象* return*/public static Point getOffsetLatLng(int zoom, Point sourcePoint)if (null = sourcePoint)return null;StringBuilder urlBuilder = new StringBuilder();urlBuilder.append(/maps/vp);urlBuilder.append(?spn=0.0,0.0);urlBuilder.append(&z=).append(zoom);urlBuilder.append(&vp=);urlBuilder.append(sourcePoint.getLatitude();/ 纬度urlBuilder.append(,);urlBuilder.append(sourcePoint.getLongitude();/ 经度HttpURLConnection httpConnection = null;try/ 1、构造HttpURLConnection连接URL url = new URL(urlBuilder.toString();URLConnection urlConnection = url.openConnection();httpConnection = (HttpURLConnection) urlConnection;httpConnection.setDoInput(true);httpConnection.setDoOutput(true);httpConnection.setConnectTimeout(CONNECT_TIMEOUT);httpConnection.connect();/ 2、接收响应结果InputStream inStream = httpConnection.getInputStream();String htmlContent = getContentByStream(inStream, REQUEST_ENCODE);/ 关闭流资源inStream.close();/ 3、解析结果String offset = parseOffsetFromZoom(zoom, htmlContent);/ 如果没有偏移值,则返回原经纬度对象if (isNullOrEmpty(offset)return sourcePoint;Point targetPoint = getOffsetPoint(offset, zoom, sourcePoint);updateProxy();(sourcePoint: + sourcePoint);(targetPoint: + targetPoint);return targetPoint; catch (Exception e)/ TODO Auto-generated catch blocke.printStackTrace();logger.error(=获取偏移经纬度信息异常!zoom = + zoom + , sourcePoint = + sourcePoint, e); finally/ 关闭连接if (null != httpConnection)httpConnection.disconnect();return null;/* 获取对应级别像素偏移量* * param zoom* param htmlContent* return*/private static String parseOffsetFromZoom(int zoom, String htmlContent)String offset = null;if (isNullOrEmpty(htmlContent) | zoom MAX_ZOOM | zoom 0 & endIndex 0)/ 获取各级别像素偏移量内容String content = htmlContent.substring(beginIndex + 1, endIndex);offset = getOffsetByZoom(zoom, content);return offset;/* 获取zoom级别的像素偏移量* * param zoom* param content* return*/private static String getOffsetByZoom(int zoom, String content)String ss = content.split(,);int index = (zoom - 10) 1) - 2;if (null = ss | ss.length (index + 1)return null;return (ssindex.trim() + , + ssindex + 1.trim();/* 获取校正后的经纬度* * param offset* param zoom* param point* return*/private static Point getOffsetPoint(String offset, int zoom, Point point)String ss = offset.split(,);int offsetX = Integer.parseInt(ss0);int offsetY = Integer.parseInt(ss1);double lngPixel = (Math.round(lngToPixel(point.getLongitude(), zoom) - offsetX); double latPixel = (Math.round(latToPixel(point.getLatitude(), zoom) - offsetY);return new Point(pixelToLng(lngPixel, zoom), pixelToLat(latPixel, zoom);/* sinLatitude = sin(latitude * pi/180)* * pixelX = (longitude + 180) / 360) * 256 * 2level* * pixelY = (0.5 log(1 + sinLatitude) / (1 sinLatitude) / (4 * pi) * 256 * 2level*/* 经度到像素X值* * param lng* param zoom* return*/private static double lngToPixel(double lng, int zoom)return (lng + 180) * (256L zoom) / 360;/* 纬度到像素Y* * param lat* param zoom* return*/private static double latToPixel(double lat, int zoom)double siny = Math.sin(lat * Math.PI / 180);double y = Math.log(1 + siny) / (1 - siny);return (256L zoom) * (0.5 - y / (4 * Math.PI);/* 像素X到经度* * param pixelX* param zoom* return*/private static double pixelToLng(double pixelX, int zoom)return pixelX * 360 / (256L zoom) - 180;/* 像素Y到纬度* * param pixelY* param zoom* return*/private static double pixelToLat(double pixelY, int zoom)double y = 4 * Math.PI * (0.5 - pixelY / (256L = 65536)/ 联通3GdataOutputStream.writeInt(5); else/ 移动3GdataOutputStream.writeInt(3);dataOutputStream.writeUTF();dataOutputStream.writeInt(cellId);dataOutputStream.writeInt(lac);dataOutputStream.writeInt(0); /mncdataOutputStream.writeInt(0); /mccdataOutputStream.writeInt(0);dataOutputStream.writeInt(0);dataOutputStream.flush();dataOutputStream.close();/* 根据地区编码(LAC)和基站编号(CID)获取地区信息* * param lac 地区编码* param cellId 基站编号* return*/public static Point getLocationByLacAndCid(int lac, int cellId)String urlString = /loc/json;HttpURLConnection httpConn = null;try/ -open a connection to Google Maps API-URL url = new URL(urlString);URLConnection conn = url.openConnection();httpConn = (HttpURLConnection) conn;httpConn.setDoOutput(true);httpConn.setDoInput(true);httpConn.setDefaultUseCaches(false);httpConn.setRequestMethod(POST);httpConn.setRequestProperty(Content-Type, application/json);httpConn.setConnectTimeout(CONNECT_TIMEOUT);httpConn.connect();/ -write some custom data to Google Maps API-OutputStreamWriter outputStream = new OutputStreamWriter(httpConn.getOutputStream();outputStream.write(getLocationRequest(lac, cellId);outputStream.flush();outputStream.close();/ -get the response-String responseContent = getContentByStream(httpConn.getInputStream(), REQUEST_ENCODE);/ -interpret the response obtained-Point point = parseLocationContent(responseContent);/(responseContent);return point; catch (Exception e)/ TODO Auto-generated catch blocke.printStackTrace();logger.error(=根据地区编码和基站编号获取地区信息异常!lac = + lac + , cellId = + cellId, e); finally/ 关闭连接if (null != httpConn)httpConn.disconnect();return null;private static String getLocationRequest(int lac, int cellId)StringBuilder requestContent = new StringBuilder();requestContent.append( );requestContent.append( version : 1.1.0, );requestContent.append( host :
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 纪委监委舆情管理办法
- 企业安全知识培训讲师课件
- 2025年深入贯彻中央八项规定精神学习教育应知应会试题及答案
- 出租屋灭火安全培训课件
- 企业安全工作培训会课件
- 出海安全培训课件
- 无人机信号安全管控技术-洞察及研究
- 2025国家能源集团内蒙古上海庙发电有限公司煤炭买卖合同
- 企业安全培训资料模板课件
- 出口退税课件介绍
- 胶质细胞瘤课件
- 校外培训消防安全知识课件
- 2025年高级执法资格考试真题及答案
- 2025浙教版(2024)八年级上册科学教学计划(三篇)
- 儿童抽动障碍的诊断与评估(2025年)解读课件
- 发热护理课件
- 2025年行政许可法知识竞赛题库及答案
- 库房管理基础知识培训课件
- 1.2《我们都是社会的一员》教学设计 2025-2026学年统编版道德与法治八年级上册
- 2024年劳动争议调解仲裁法知识竞赛题库与答案
- 劳动与技术小学开学第一课
评论
0/150
提交评论