1. 程式人生 > >整理了一份谷歌地址校驗查詢的案例。

整理了一份谷歌地址校驗查詢的案例。

都知道谷歌很牛逼。自從用了他的地址校驗,別的我都不想用了。

程式碼

package com.yiexpress.core.utils.aupost;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;












import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.util.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yiexpress.aupost.dto.googlebean.AddressComponents;
import com.yiexpress.aupost.dto.googlebean.GoogleGeocodeJSONBean;
import com.yiexpress.aupost.dto.googlebean.Results;
import com.yiexpress.cainiao.config.CainiaoConstants;
import com.yiexpress.core.utils.AnJieUtils;
import com.yiexpress.core.utils.DictUtils;
import com.yiexpress.core.utils.FormatUtils;
import com.yiexpress.core.utils.HttpUtils;



 

/**
 * 
 * @author Martin
 *
 */
public final class GoogleGeocoderUtil {
	public static final int ADDRESS = 1;
	public static final int LATLNG = 2;
	private final static String GOOGLEAPIURL="https://ditu.google.cn";
	private static final Logger LOGGER=LoggerFactory.getLogger(GoogleGeocoderUtil.class);

	private static final ObjectMapper jsonMapper=new ObjectMapper();
	/**
	 * 
	 * @param address 座標(123123,12312)這種方式,)或者直接地址address="12321,2312" address="上海市普陀區" 
	 * @param lang null時以en為準 語言
	 * @return
	 * @throws Exception
	 */
	public static GoogleGeocodeJSONBean geocodeByAddress(String address,String lang) throws Exception{
		if(StringUtils.isBlank(lang)){
			lang="en";
		}
		LOGGER.info("谷歌地址解析開始:");
		String path="/maps/api/geocode/json";
		
		Map<String, String> body = new HashMap<String, String>();
		body.put("language", lang);
		body.put("sensor", "false");
		body.put("address", address);
		body.put("key", CainiaoConstants.GOOGLE_API_KEY);
		JSONObject object=null;
		try {
			HttpResponse response =HttpUtils.doPost(GOOGLEAPIURL, path, DictUtils.GET_METHOD, new HashMap<String, String>() ,body,  new HashMap<String, String>());
			object = ChEnUtils.getJsonByRes(response);
			GoogleGeocodeJSONBean bean = jsonMapper.readValue(object.toString(), GoogleGeocodeJSONBean.class);
			//LOGGER.info(object.toString());
			return bean;
		
		} catch (Exception e) {
			LOGGER.info("請求發生了錯誤!==>{}",e);
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
	  	
		try {
			// NORTH LAKES QLD	LJ Hooker North Lakes
//			String info=GoogleGeocoderUtil.checkAddrIsCorrect("CN","湖南省","株洲","中心廣場百貨大樓","412000","CN",true);
//			System.out.println(info);
			GoogleGeocoderUtil.geocodeByAddress("上海三門路青新公寓", "CN");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println(checkAddrIsCorrect("AU", "NSW", "Greenacre", null,"2190", "en"));
		//System.out.println("AU".contains("A"));
	}
	/**
	 * 校驗地址的準確性 
	 * @param country 國家
	 * @param state 省/州
	 * @param suburb 城市
	 * @param stream 地址
	 * @param postCode 郵編
	 * @param lang 語言
	 * @param isValidStream 是否校驗地址
	 * @return
	 */
	public static String checkAddrIsCorrect(String country,String state,String suburb,String stream,String postCode,String lang,boolean isValidStream){
		String result = DictUtils.SUCCESS;
		String address=stream+","+suburb+","+state+","+country;
		LOGGER.info("您的地址是:{}",address);
		GoogleGeocodeJSONBean info;
		try {
			info = GoogleGeocoderUtil.geocodeByAddress(address, lang);
		} catch (Exception e) {
			LOGGER.info("系統發生錯誤,請聯絡管理員(網路錯誤)或者解析javabean錯誤)!==>{}",e);
			return "系統發生錯誤,請聯絡管理員!";
		}
		if("OK".equalsIgnoreCase(info.getStatus())){
			
			if(info.getResults()==null||info.getResults().size()==0){
				return "請填寫正確的地址";
			}
			Results googleResult = info.getResults().get(0);
			List<AddressComponents> addressCom = googleResult.getAddress_components();
			
			// 遍歷返回的地址資訊
			String googleShortCountry=null;
			String googleShortState=null;
			String googleShortsuburb=null;
			String googleShortTown=null;
			String googleShortStream=null;
			String googleShortStreamNumber=null;
			String googleLongCountry=null;
			String googleLongState=null;
			String googleLongsuburb=null;
			String googleLongTown=null;
			String googleLongStream=null;
			String googleLongStreamNumber=null;
			String googlePostCode=null;
			for(AddressComponents addressComponent:addressCom){
				if(addressComponent.getTypes()[0].equalsIgnoreCase("country")){
					googleShortCountry = addressComponent.getShort_name();
					googleLongCountry = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("administrative_area_level_2")){
					googleShortState = addressComponent.getShort_name();
					googleLongState = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("postal_town")){
					googleShortTown = addressComponent.getShort_name();
					googleLongTown = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("locality")){
					googleShortsuburb = addressComponent.getShort_name();
					googleLongsuburb = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("route")){
					googleShortStream = addressComponent.getShort_name();
					googleLongStream = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("street_number")){
					googleShortStreamNumber = addressComponent.getShort_name();
					googleLongStreamNumber = addressComponent.getLong_name();
				}
				else if(addressComponent.getTypes()[0].equalsIgnoreCase("postal_code")){
					googlePostCode = addressComponent.getShort_name();
					
				}
				
			}
			
			// 定製 為英國GB 校驗郵編和城市 沒有州 無法校驗
//			if("GB".equalsIgnoreCase(validCountry)){
				// 首先校驗國家,省州,城市是否匹配
				if(StringUtils.isNotBlank(country)&&StringUtils.isNotBlank(googleLongCountry)&&!(country.equalsIgnoreCase(googleLongCountry)||country.equalsIgnoreCase(googleShortCountry))){
					return "國家不匹配,結果:全名("+googleLongCountry +" )或者縮寫名("+googleShortCountry+")。您的:"+country;
				}
				/*if(StringUtils.isNotBlank(state)&&StringUtils.isNotBlank(googleLongState)&&!(state.equalsIgnoreCase(googleLongState)||state.equalsIgnoreCase(googleShortState))){
					return "省/州(地區)不匹配,結果:全名("+googleLongState +" )或者縮寫名("+googleShortState+")。您的:"+state;
				}*/
				if(StringUtils.isNotBlank(suburb)&&StringUtils.isNotBlank(googleLongTown)&&!(suburb.equalsIgnoreCase(googleLongsuburb)||suburb.equalsIgnoreCase(googleShortsuburb))){
					// 如果連鎮都不匹配
					if(googleLongsuburb==null&&googleShortsuburb==null){
						if(!(suburb.equalsIgnoreCase(googleLongTown)||suburb.equalsIgnoreCase(googleShortTown))){
							return "城市(地市)不匹配,結果:全名("+googleLongTown +" )或者縮寫名("+googleShortTown+")。您的:"+suburb;
						}
					}else{
						return "城市(地市)不匹配,結果:全名("+googleLongsuburb +" )或者縮寫名("+googleShortsuburb+")。您的:"+suburb;
					}
					
					
				}
				

				String shortStream = googleShortStreamNumber+" "+googleShortStream;
				String longStream = googleLongStreamNumber+" "+googleLongStream;
				
				
				if(isValidStream){
					if(googleShortStreamNumber==null||googleLongStream==null){
						return "請填寫正確的地址!";
					}
					if(StringUtils.isNotBlank(shortStream)&&
						!(
								AnJieUtils.trim(stream.toUpperCase()).contains(AnJieUtils.trim(shortStream.toUpperCase()))
								||AnJieUtils.trim(stream.toUpperCase()).contains(AnJieUtils.trim(longStream.toUpperCase())))
								){
					return "街道地址不包含,結果:全名("+longStream +" )或者縮寫名("+shortStream+")。您的:"+stream;
					}
				}

						
				if(StringUtils.isNotBlank(postCode)&&!AnJieUtils.trim(postCode).equalsIgnoreCase(AnJieUtils.trim(googlePostCode))){
					if(googlePostCode==null){
						return "請填寫正確的地址!";
					}
					return "郵編不匹配,結果:"+googlePostCode+" 。您的:"+postCode;
				}
//			}
		}else{
			return "地址不存在,請檢查您輸入的地址";
		}
		
		return result;
		
	}

}

以上是一份案例。對英國地址進行校驗的案例。

如果你剛好,需要,也不需要吝嗇。

對於谷歌返回引數:

 {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Pkwy",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara",
               "short_name" : "Santa Clara",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.42291810,
               "lng" : -122.08542120
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.42426708029149,
                  "lng" : -122.0840722197085
               },
               "southwest" : {
                  "lat" : 37.42156911970850,
                  "lng" : -122.0867701802915
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"

請參考連結 說明這是引數說明