Java 调用Google Map Api解析地址,解析经纬度实例

Java 调用Google Map Api解析地址,解析经纬度实例
使用google地图的反向地址解析功能,提供一个经纬度得到对应地址,或者给出模糊地址,得到经纬度,放在java后台代码中处理,这个使用的是Google的地理编码服务。一般而言数据量不大的情况使用是不限制的。按照Google官方说法是连续90天请求地理编码服务次数超过2000次就会受到限制,因此可以将这些解析好的地址放在Database中,这样可以避免重复请求同一个地址。
JAVA Code:
/*
* System Abbrev :
* system Name  :
* Component No  :
* Component Name:
* File name     :GoogleGeocoderUtil.java
* Author        :Peter.Qiu
* Date          :2014-9-18
* Description   :  <description>
*/

/* Updation record 1:
 * Updation date        :  2014-9-18
 * Updator          :  Peter.Qiu
 * Trace No:  <Trace No>
 * Updation No:  <Updation No>
 * Updation Content:  <List all contents of updation and all methods updated.>
 */
package com.qiuzhping.google;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.qiuzhping.google.beans.GoogleGeocodeJSONBean;

/**
 * <Description functions in a word>
 * type :1-->address 2-->latlng
 * <Detail description>
 * 
 * @author  Peter.Qiu
 * @version  [Version NO, 2014-9-18]
 * @see  [Related classes/methods]
 * @since  [product/module version]
 */
public final class GoogleGeocoderUtil {
	public static final int ADDRESS = 1;
	public static final int LATLNG = 2;
	private final String GOOGLEAPIURL="http://maps.googleapis.com/maps/api/geocode/json?language=en&sensor=true";
	private Logger log = Logger.getLogger(GoogleGeocoderUtil.class.getName());
	private int type ;//1-->address 2-->latlng
	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}
	private static GoogleGeocoderUtil instance;
	
	public static GoogleGeocoderUtil getInstance() {
		if(instance == null){
			instance = new GoogleGeocoderUtil();
		}
		return instance;
	}

	/** <Description functions in a word>
	 * 2014-9-18
	 * <Detail description>
	 * @author  Peter.Qiu
	 * @param address 
	 * @return
	 * @return GoogleGeocodeJSONBean [Return type description]
	 * @throws Exception 
	 * @exception throws [Exception] [Exception description]
	 * @see [Related classes#Related methods#Related properties]
	 */
	public GoogleGeocodeJSONBean geocodeByAddress(String address) throws Exception{
		if(address == null || address.equals("")){
			return null;
		}
		log.info("geocode By Address : "+address);
		log.info("Start geocode");
		GoogleGeocodeJSONBean bean = null;
		BufferedReader in= null;
		HttpURLConnection httpConn = null;
		try {
			log.info("Start open url");
			String urlPath = GOOGLEAPIURL+"&address="+URLEncoder.encode(address,"UTF-8");;
			if(this.getType() == LATLNG){
				urlPath = GOOGLEAPIURL+"&latlng="+address;
			}
			log.info("url : "+urlPath);
			URL url = new URL(urlPath);
			httpConn = (HttpURLConnection) url.openConnection(); 
			log.info("End open url");
			httpConn.setDoInput(true);   
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));   
		    String line;
		    String result="";
		    while ((line = in.readLine()) != null) {   
		        result += line;   
		    }   
		    in.close();
		    //httpConn.disconnect();
		    JSONObject jsonObject = JSONObject.fromObject( result );
		    bean = (GoogleGeocodeJSONBean) JSONObject.toBean( jsonObject, GoogleGeocodeJSONBean.class );
		    if(bean != null && bean.status.equalsIgnoreCase("ok") && bean.results != null && bean.results[0].geometry.getLocation() != null){
		    	log.info("Start display Geocode info");
		    	log.info("Formatted Address :" + bean.results[0].getFormatted_address());
		    	log.info("geometry Location : " + bean.results[0].geometry.getLocation().getLat() + ","+bean.results[0].geometry.getLocation().getLng());
			    log.info("End display Geocode info");
		    }
		    log.info("End geocode");
		    return bean;
		} catch (MalformedURLException e) {
			log.error(e);
			throw e;
		} catch (IOException e) {
			log.error(e);
			throw e;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					log.error(e);
					throw e;
				}
			}
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}
	}
	
	public String getGoogleLongitudeDimensions(GoogleGeocodeJSONBean googleBean) throws IOException{
		if (googleBean != null &&  googleBean.status.equalsIgnoreCase("ok")
				&& googleBean.results[0] != null
				&& googleBean.results[0].formatted_address != null
				&& googleBean.results[0].getGeometry().location != null
				&& googleBean.results[0].getGeometry().location.getLat() != null
				&& googleBean.results[0].getGeometry().location.getLng() != null) {
			String formatted_Address = googleBean.results[0].formatted_address;
			String location = googleBean.results[0].getGeometry().location.getLat()+","+googleBean.results[0].getGeometry().location.getLng();
			return formatted_Address.trim()+"|"+location;
		}
		return null;
	}
	/** <Description functions in a word>
	 * 2014-9-18
	 * <Detail description>
	 * @author  Peter.Qiu
	 * @param args [Parameters description]
	 * @return void [Return type description]
	 * @throws Exception 
	 * @exception throws [Exception] [Exception description]
	 * @see [Related classes#Related methods#Related properties]
	 */
	public static void main(String[] args) throws Exception {
		try {
			getInstance().setType(2);
			GoogleGeocodeJSONBean bean = getInstance().geocodeByAddress("39.90403,116.407526");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

完整的Demo:Java 调用Google Map Api解析地址,解析经纬度实例
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要在高德地图开放平台申请一个 API Key,用于在你的应用程序中调用高德地图的 API。 然后,你可以使用高德地图的 JavaScript API实现根据地址解析经纬度并展示位置的功能。以下是一个简单的示例代码: 1. 在 nuxt.config.js 文件中添加高德地图的 API Key: ```javascript module.exports = { // ... env: { amapApiKey: 'your_amap_api_key' } // ... } ``` 2. 在你的组件中引入高德地图的 JavaScript API: ```javascript import AMapLoader from '@amap/amap-jsapi-loader' export default { data() { return { map: null, marker: null } }, async mounted() { const AMap = await AMapLoader.load({ key: this.$config.amapApiKey, version: '2.0', plugins: ['AMap.Geocoder', 'AMap.Marker'] }) const address = '北京市朝阳区望京SOHO' const geocoder = new AMap.Geocoder() geocoder.getLocation(address, (status, result) => { if (status === 'complete' && result.geocodes.length) { const location = result.geocodes[0].location this.map = new AMap.Map('map-container', { center: location, zoom: 16 }) this.marker = new AMap.Marker({ position: location, map: this.map }) } else { console.error('Geocode failed:', status, result) } }) } } ``` 上述代码中,我们使用 AMapLoader 异步加载高德地图的 JavaScript API,并在组件的 mounted 钩子函数中调用 AMap.Geocoder 的 getLocation 方法来解析地址。如果解析成功,我们创建一个 AMap.Map 实例并在地图上添加一个 AMap.Marker 标记来展示位置。 3. 在模板中添加地图容器: ```html <template> <div> <div id="map-container" style="width: 100%; height: 500px;"></div> </div> </template> ``` 注意:上述代码中的 `address` 变量应该替换为你需要解析地址。另外,如果你需要在组件销毁时清除地图,可以在 beforeDestroy 钩子函数中调用 `this.map.destroy()` 方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值