바 이 두 맵 에서 경 위 를 가 져 오고 주 소 를 가 져 옵 니 다.

2888 단어 자바
package com.hst.web.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.springframework.util.StringUtils;

public class BaiDuMapUnit {
	/**
	 *             key lng(  ),lat(  )
	 */
	public static void getGeocoderLatitude(String address) {
		BufferedReader in = null;
		try {
			address = URLEncoder.encode(address, "UTF-8");
			URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak="
					+ "dVeyh7XGPHUsoAmcaltrHCiP&location"+"&callback=showLocation");
			in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
			String res;
			StringBuilder sb = new StringBuilder("");
			while ((res = in.readLine()) != null) {
				sb.append(res.trim());
			}
			String str = sb.toString();
			if (!StringUtils.isEmpty(str)) {
				int lngStart = str.indexOf("lng\":");
				int lngEnd = str.indexOf(",\"lat");
				int latEnd = str.indexOf("},\"precise");
				if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
					String lng = str.substring(lngStart + 5, lngEnd);
					String lat = str.substring(lngEnd + 7, latEnd);
					System.out.println("lng:" + lng + "    lat:" + lat);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *           key lng(  ),lat(  )
	 */
	public static String getPosition(String latitude, String longitude) throws MalformedURLException {
		BufferedReader in = null;
		URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + latitude + "," + longitude
				+ "&output=json&pois=1&ak=" + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR");
		try {
			in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
			String res;
			StringBuilder sb = new StringBuilder("");
			while ((res = in.readLine()) != null) {
				sb.append(res.trim());
			}
			String str = sb.toString();
			//System.out.println(str);
			if (!StringUtils.isEmpty(str)) {
				int lngStart = str.indexOf("formatted_address\":\"");
				int lngEnd = str.indexOf("\",\"business");
				if (lngStart > 0 && lngEnd > 0 ) {
					String ads = str.substring(lngStart + 20, lngEnd);
					return ads;
//					System.out.println("ads:" + ads);
				}
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

좋은 웹페이지 즐겨찾기