Get latitude and longitude according to address

Source: Internet
Author: User
Tags sin
Package com.maputil;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;

Import Java.util.Map.Entry;
	public class Addresslatlngutil {private 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_split_str = ",";
	public static final int min_zoom = 11; public staticFinal int max_zoom = 18;
	private static final int downnum_for_proxy = 8000; private static final int connect_timeout = 30000;
	30 seconds private static final int thread_sleep_millis = 200;
	private static Boolean flag = FALSE;
	private static int downnum = 0;
	private static String ProxyHost = "165.228.128.10";
	private static String ProxyPort = "3128";

	private static String Proxyset = "true"; 
	 /** * Obtain address details and latitude information * @Title: GETADDRESSLATLNG * @param address * @return map<string,point>< addresses, Latitude > * @author: Zhengxingmiao * @time: Nov 1, 10:29:53 AM */public static map<string, point> getaddresslatln
		G (String address) {StringBuilder UrlBuilder = new StringBuilder ();
		Urlbuilder.append ("Http://ditu.google.cn/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 ("&AMP;HL=ZH-CN");
		Urlbuilder.append ("&callback=_xdc_._1g4gm5mh3");
		System.out.println (UrlBuilder);
		HttpURLConnection httpconnection = null;
			try {//1 construct httpurlconnection connection 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 Receive response results InputStream instream = Httpconnection.getinputstream ();
			String htmlcontent = Getcontentbystream (instream, Request_encode);

			Turn off Flow resource instream.close ();
			3 analytic results map<string, point> Map = PARSEADDRESSLATLNG (htmlcontent);
			Updateproxy ();
		return map;
			catch (Exception e) {e.printstacktrace (); System.out.println ("=========== get latitude and longitude information anomaly."
Request: "+ address";			return Java.util.Collections.emptyMap ();
			Finally {//close connection if (null!= httpconnection) {httpconnection.disconnect (); /** * Address Information transcoding * @Title: encodeURLForUTF8 * @param str * @return String * @author: Zhengxingmiao * @t Ime:nov 1 10:32:16 AM */private static string EncodeURLForUTF8 (String str) {try {str = java.net.URLEncod
		Er.encode (str, "UTF-8");
			catch (Unsupportedencodingexception e) {e.printstacktrace ();
		System.out.println ("string-transcoding exception, string:" + str);
	return str; /** * Reads the information from the stream according to the specified encoding * @Title: Getcontentbystream * @param instream * @param encode * @return * @throws IO Exception String * @author: Zhengxingmiao * @time: Nov 1, 10:32:46 AM */private static String Getcontentbystre
		AM (InputStream instream, String encode) throws IOException {if (null = = instream) {return null;
		} StringBuilder content = new StringBuilder (); Reads stream content in the specified encoding format BufferedReader reader = new BufferedreadER (new InputStreamReader (instream, encode));
		String message = NULL;
			while (null!= (message = Reader.readline ())) {content.append (message);
		Content.append ("\ r \ n");
		//Close Reader, Release resource Reader.close ();
	Return (content.tostring ()); /** * Resolution of Web page content address information and latitude information * @Title: PARSEADDRESSLATLNG * @param htmlcontent * @return map<string,point>&lt ; address, Latitude > * @author: Zhengxingmiao * @time: Nov 1, 10:33:59 AM/private static map<string, Point> PA
		RSEADDRESSLATLNG (String htmlcontent) {map<string, point> addr = new hashmap<string, point> (1);
		if (IsNullOrEmpty (htmlcontent)) {return addr;
		} string[] contents = Htmlcontent.split ("\ r \ n");
		string[] ss = NULL;
		String address = null;
		String country = null;
		String region = null;
		String city = null;
		Point point = NULL;
			for (String line:contents) {if (IsNullOrEmpty) {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 (ss[1], "[", "]");
					string[] pss = Pointstr.split (",");
						if (null!= PSS && pss.length > 1) {double defaultvalue = 0 D; Point = new Point (IsNullOrEmpty (Pss[0]) defaultValue:Double.parseDouble (Pss[0].trim ()), IsNullOrEmpty ( PSS[1])?
					Defaultvalue:double. Parsedouble (Pss[1].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); ///default to first address information if (false = IsNullOrEmpty (address) && null!= point) {point.setcountry (country);
				Point.setregion (region);
				Point.setcity (city);
			Break
		}//end-for-contents//If the address is not empty if (false = IsNullOrEmpty (addresses)) {Addr.put (addressing, point);
	return addr; /** * Base site information access latitude and longitude * @Title: GETADDRESSLATLNG * @param addresslist Address collection * @return LIST&LT;MAP&LT;STRING,POINT&G t;><map< address, Latitude object >> * @author: Zhengxingmiao * @time: Nov 1, 10:35:23 AM/public static LIST&L T  Map<string, point>> getaddresslatlng (list<string> addresslist) {list<map<string, Point>>
		List = new arraylist<map<string, point>> ();
		if (null = = AddressList | | addresslist.isempty ()) {return list;
			for (String address:addresslist) {try {//Break thread.sleep (Thread_sleep_millis);
			catch (Interruptedexception e) {e.printstacktrace ();
			} map<string, point> Addrmap = getaddresslatlng (address);
	if (false = = Addrmap.isempty ()) {			List.add (ADDRMAP); else {System.out.println ("=========== get latitude and longitude information is empty.")
			Request: "+ address";
	} return list; /** * Get the middle string content * @Title: GETMIDDLESTR * @param content * @param beginstr * @param endstr * @return Strin G * @author: Zhengxingmiao * @time: Nov 1, 10:36:22 AM */private static string Getmiddlestr (string content, St
		Ring 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 ()). In
			Dexof (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 = "Http.proxyhost";
	private static final String Proxy_port_key = "Http.proxyport";

	private static final String Proxy_set_key = "Http.proxyset";
		Switch agent private static synchronized void Updateproxy () {downnum++;
				if (downnum% Downnum_for_proxy = = 0) {if (flag) {clearproxy ();
			Flag = false;
				else {setproxy ();
			Flag = true;
		}} private static void SetProxy () {System.setproperty (Proxy_host_key, proxyhost);
		System.setproperty (Proxy_port_key, ProxyPort);
		System.setproperty (Proxy_set_key, Proxyset);
	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);
	System.out.println ("clearproxy====="); /** * Get offset latitude and longitude (Google China map offset interface) China maps and satellite maps are offset, this is determined by the China Planning Bureau, * Google's map services, to ditu.gogle the beginning of theThere is deviation, the service that starts with Maps.google has deviation * @Title: GETOFFSETLATLNG * @param zoom offset level (from level 11 to 18, 18 most accurate) * @param sourcepoint latitude and longitude objects  * @return Point * @author: Zhengxingmiao * @time: Nov 1, 10:37:54 AM */public static point getoffsetlatlng (int
		Zoom, point Sourcepoint) {if (null = = Sourcepoint) {return null;
		} StringBuilder UrlBuilder = new StringBuilder ();
		Urlbuilder.append ("HTTP://DITU.GOOGLE.CN/MAPS/VP");
		Urlbuilder.append ("? spn=0.0,0.0");
		Urlbuilder.append ("&z="). append (zoom);
		Urlbuilder.append ("&vp=");
		Urlbuilder.append (Sourcepoint.getlatitude ());//Latitude Urlbuilder.append (",");
		
		Urlbuilder.append (Sourcepoint.getlongitude ()),//longitude httpurlconnection httpconnection = null;
			try {//construct httpurlconnection connection 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 ();
			Receive response results InputStream instream = Httpconnection.getinputstream ();
			String htmlcontent = Getcontentbystream (instream, Request_encode);
			Turn off Flow resource instream.close ();
			Parse result String offset = parseoffsetfromzoom (zoom, htmlcontent);
			If there is no offset value, returns the original Latitude object if (IsNullOrEmpty (offset)) {return sourcepoint;
			Point targetpoint = getoffsetpoint (offset, zoom, sourcepoint);
			Updateproxy ();
			System.out.println ("Sourcepoint:" + sourcepoint);
			System.out.println ("TargetPoint:" + targetpoint);
		return targetpoint;
			catch (Exception e) {e.printstacktrace (); System.out.println ("===========) obtains an offset longitude and latitude information exception.
		Zoom = "+ Zoom +", Sourcepoint = "+ Sourcepoint");
			Finally {//close connection if (null!= httpconnection) {httpconnection.disconnect ();
	} return null; /** * Get corresponding level pixel offset * @Title: Parseoffsetfromzoom * @param zoom * @param htmlcontent * @return String * @author: Zhengxingmiao * @time: Nov 1, 10:39:52 AM */private static String parseoffsetfromzoom (int zoom, String
		htmlcontent) {String offset = null;
		if (IsNullOrEmpty (htmlcontent) | | | Zoom > Max_zoom | | Zoom < min_zoom) {return offset; } * * below, respectively, latitude and longitude, level, offset pixel quantity "level from 11 to 18, total 8 groups of numbers" * The previous set of numbers is exactly equal to the last set of digits except two, we select the 18th-level offset 1193,-270 for the most accurate offset, * 1193 is in x direction Offset pixel of precision,-270 is the dimension offset pixel in the y direction * * window. Gtileshiftupdateoffset && windows. Gtileshiftupdateoffset (* 39.111195, 117.148067, 18, [9,-2, 18,-4, 37,-8, 74,-16, 149,-33, * 298,-67, 596,-13
		 5, 1193,-270]);
		* * int beginindex = Htmlcontent.lastindexof ("[");
		int endindex = Htmlcontent.lastindexof ("]"); if (Beginindex > 0 && endindex > 0) {//Get all levels pixel offset content String content = htmlcontent.substring (begininde
			x + 1, endindex);
		offset = getoffsetbyzoom (zoom, content);
	return offset; /** * Get zoom level pixel offset * @Title: Getoffsetbyzoom * @param zoom * @param cOntent * @return String * @author: Zhengxingmiao * @time: Nov 1, 10:40:21 AM */private static String getoffs
		Etbyzoom (int zoom, String content) {string[] ss = Content.split (",");
		int index = ((zoom-10) << 1)-2;
		if (null = SS | | Ss.length < (index + 1)) {return null;
	Return (Ss[index].trim () + "," + Ss[index + 1].trim ());  /** * Obtain corrected latitude and longitude * @Title: Getoffsetpoint * @param offset * @param zoom * @param point * @return Point * @author: Zhengxingmiao * @time: Nov 1 10:40:28 AM */private static point Getoffsetpoint (String offset, int zoo
		M, point Point) {string[] ss = Offset.split (",");
		int OffsetX = Integer.parseint (Ss[0]);

		int OffsetY = Integer.parseint (ss[1]);
		Double Lngpixel = (Math.Round (Lngtopixel (Point.getlongitude (), zoom))-OffsetX);
		Double Latpixel = (Math.Round (Lattopixel (Point.getlatitude (), zoom))-OffsetY);
	Return to 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//** * Longitude to pixel x value * @Title: Lngtopixel * @param LNG * @param zoom * @return Double * @author: Zhengxingmiao * @time: Nov 1, 10:41:18 AM * * priv
	Ate static double Lngtopixel (double LNG, int zoom) {return (LNG + 180) * (256L << zoom)/360;  /** * latitude to Pixel y * @Title: Lattopixel * @param lat * @param zoom * @return Double * @author: Zhengxingmiao * @time: Nov 1, 10:41:07 AM */private static double Lattopixel (double lat, int zoom) {Double siny = Math.sin (LA
		T * math.pi/180);
		Double y = Math.log ((1 + siny)/(1-siny));
	Return (256L << zoom) * (0.5-y/(4 * math.pi));
	 /** * pixel x to Longitude * @Title: PIXELTOLNG * @param pixelx * @param zoom * @return Double * @author: Zhengxingmiao
* @time: Nov 1, 10:41:33 AM	 * * private static double pixeltolng (double pixelx, int zoom) {return PIXELX * 360/(256L << Zoom)-180;
	 /** * Pixel y to Latitude * @Title: Pixeltolat * @param pixely * @param zoom * @return Double * @author: Zhengxingmiao * @time: Nov 1, 10:41:38 AM */private static double Pixeltolat (double pixely, int zoom) {Double y = 4 * Math .
		PI * (0.5-pixely/(256L << zoom));
		Double z = Math.pow (math.e, y);
		Double siny = (z-1)/(z + 1);
	Return Math.asin (siny) * 180/MATH.PI; /** * Get value * @Title: GetValue * @param content * @param key * @return String * @author: Zhengxingmiao * @time: Nov 1, 10:42:48 AM */private static string GetValue (string content, string key) {if (false = = Isnullore
			Mpty (content) && false = = IsNullOrEmpty (key)) {string[] ss = Content.split ("\ r \ n");
				for (String line:ss) {if (IsNullOrEmpty) {continue; line = Line.replace ("{", ""). Replace ("}", ""). Replace ("["," "). Replace ("] "," "). Trim ();
				string[] sss = Line.split (LOCATION_SPLIT_STR);
					for (String str:sss) {if (IsNullOrEmpty (str) | | | false = = Str.contains (key)) {continue;
					} string[] Sub = str.split (ADDRESS_SPLIT_STR);
						for (int i = 0; i < sub.length i++) {if (IsNullOrEmpty (sub[i))) {continue;
					} Sub[i] = Sub[i].trim ();
					} list<string> sublist = Java.util.Arrays.asList (sub);
					int subindex = Sublist.indexof (key);
						if ( -1!= subindex && sublist.size () > (subindex + 1)) {String value = sublist.get (subindex + 1);
					Return (Value.replace ("\", ""). Trim ());
	}}//end-for-sss}//end-for-ss} return null; /** * To determine if the string is null * @Title: IsNullOrEmpty * @param str * @return Boolean * @author: Zhengxingmiao * @time: N OV 1 10:43:11 AM */public static Boolean IsNullOrEmpty (String str) {if (null = = STR | |
		". Equals (str)) {return true;
	}	return false;

		/** * Latitude and longitude coordinates information/public static class Point {/** * Longitude/private double longitude;

		/** * Latitude * * private double latitude;

		/** * Precision * * private double precision;

		/** * Country * * Private String country;

		/** * Province * * Private String region;

		/** * City/private String; /** * <p>title: </p> * <p>description: </p> * @param longitude longitude * @param latitude weft
			Degree */public point (double longitude, double latitude) {this.longitude = longitude;
		This.latitude = latitude;
		Public double Getlongitude () {return longitude;
		The public void Setlongitude (double longitude) {this.longitude = longitude;
		Public double Getlatitude () {return latitude;
		The public void Setlatitude (double latitude) {this.latitude = latitude;
		Public double getprecision () {return precision; } public void Setprecision (double precision) {This.precision = precision;
			Public String toString () {StringBuilder content = new StringBuilder ();
			Content.append (GetClass (). GetName ());
			Content.append ("[latitude=");
			Content.append (This.latitude);
			Content.append (", longitude=");
			Content.append (This.longitude);
				if (this.precision!= 0.0) {content.append (", precision=");
			Content.append (this.precision);
				} if (false = = IsNullOrEmpty (this.country)) {content.append (", country=");
			Content.append (This.country);
				} if (false = = IsNullOrEmpty (this.region)) {content.append (", region=");
			Content.append (this.region);
				} if (false = = IsNullOrEmpty (this.city)) {content.append (", city=");
			Content.append (this.city);
			} content.append ("]");
		Return (content.tostring ());
		Public String Getcountry () {return country;
		} public void Setcountry (String country) {this.country = country;
		Public String getregion () {return region; } public void SETregion (String region) {this.region = region;
		Public String getcity () {return city;
		public void Setcity (String city) {this.city = city;
	} public static String Getproxyhost () {return proxyhost;
	The public static void Setproxyhost (String proxyhost) {addresslatlngutil.proxyhost = ProxyHost;
	public static String Getproxyport () {return proxyport;
	The public static void Setproxyport (String proxyport) {addresslatlngutil.proxyport = ProxyPort; /** * Test * @param args/public static void main (string[] args) {list<string> addrlist = new Arrayli
		St<string> ();

		Addrlist.add ("Shijiazhuang City, Hebei province");
		list<map<string, point>> list = GETADDRESSLATLNG (addrlist);
				For (map<string, point> map:list) {for (entry<string, point> entry:map.entrySet ()) {//Get offset coordinates
				Point offsetpoint = GETOFFSETLATLNG (Max_zoom, Entry.getvalue ());
				System.out.println ("Latitude:" + offsetpoint.longitude); System.out.prinTLN ("Longitude:" + offsetpoint.latitude);
	}//system.out.println ("finished!"); }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.