安卓Webview引用谷歌web地图

         前段时间由于需求问题需要用到谷歌地图,因为百度地图在国外就是一片片空白,所以只能用谷歌的,然而谷歌地图有个缺点,国产手机上基本上都不支持原生态app谷歌地图,几乎所有国产手机都把Google service服务去掉了,所以手机app类型的谷歌地图无法使用,当然你可以把谷歌的服务安装回来,不过这不是每个人都愿意这么做的!

    于是乎寻求另外一种方式:WebApp!把地图做成网页类型的,然后通过android的WebView控件来实现调用,目前android的sdk版本足以支持css、html、js的使用。当然,我百度谷歌了很多资料,只有一个比较满意的例子说明,当也仅仅是说明,不过对我帮助还挺大的,我把出处贴上来吧:http://blog.csdn.net/wolf_jr/article/details/6738182      果断的把这例子照着添加一次!结果...bullshit!我不知道该怎么引用!小白菜一颗!折腾了好久,最后终于明白了!下面我就引用这个大哥(他其实转的别人的文章)的一些见解,给大伙说说 How to use Google maps for Android!
      前段时间由于需求问题需要用到谷歌地图,因为百度地图在国外就是一片片空白,所以只能用谷歌的,然而谷歌地图有个缺点,国产手机上基本上都不支持原生态app谷歌地图,几乎所有国产手机都把Google service服务去掉了,所以手机app类型的谷歌地图无法使用,当然你可以把谷歌的服务安装回来,不过这不是每个人都愿意这么做的!

首先把做好的html代码给大家贴上来:

Map.html   第六行src="maps.google.com/maps/api/js?sensor=true",在maps前面再加上http://  我也不知道csdn干嘛了!不给添加正常链接地址!

<html>

<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

<title>Google Web Map for Android</title>

<script type="text/javascript" src=""></script>

<script type="text/javascript">

var directionsDisplay;

var directionsService = new google.maps.DirectionsService();

var map;

function initialize() {

directionsDisplay = new google.maps.DirectionsRenderer();

var latitude = 39.904214;

var longitude = 116.40741300000002;

var myLatlng = new google.maps.LatLng(latitude,longitude);

var myOptions = {

zoom: 8,

center: myLatlng,

mapTypeId: google.maps.MapTypeId.ROADMAP

}

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

directionsDisplay.setMap(map);

}

function calcRoute() {

var start = document.getElementById('start').value;

var end = document.getElementById('end').value;

var mode;

if(document.getElementById('mode').value=="DRIVING"){

mode=google.maps.TravelMode.DRIVING;

}else if(document.getElementById('mode').value=="BICYCLING"){

mode=google.maps.TravelMode.BICYCLING;

}else if(document.getElementById('mode').value=="TRANSIT"){

mode=google.maps.TravelMode.TRANSIT;

}else{mode=google.maps.TravelMode.WALKING;}

var request = {

origin:start,

destination:end,

travelMode: mode

};

directionsService.route(request, function(response, status) {

if (status == google.maps.DirectionsStatus.OK) {

directionsDisplay.setDirections(response);

}

});

}

function centerAt(latitude, longitude){

myLatlng = new google.maps.LatLng(latitude,longitude);

map.panTo(myLatlng);

}

google.maps.event.addDomListener(window, 'load', initialize);

</script>

</head>

<body style="margin:0px; padding:0px;">

<div id="Search">

<b>Start: </b>

<input id="start" type="text" value="北京"/>

<b>End: </b>

<input id="end" type="text" value="天津"/>

<select id="mode">

<option value="DRIVING">标准路线</option>

<option value="BICYCLING">骑行路线</option>

<option value="TRANSIT">公交路线</option>

<option value="WALKING">步行路线</option>

</select>

<input id="end" type="button" value="search" οnclick="javascript:calcRoute();"/>

</div>

<div id="map_canvas" style="width:100%; height:100%"></div>

</body>

</html>

这个是我添加了线路搜索功能的web页面。可以直接当做网页使用,在电脑上用浏览器打开就可以看到!现在把这个页面放到app项目的asset文件夹下!然后,借用下人家的讲解:在手机app项目里加上webview
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
  <WebView android:id="@+id/webview" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"/> 
</LinearLayout>

下面添加权限:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

在主Activity里的代码如下:

@SuppressLint("JavascriptInterface")
public class MainActivity extends Activity implements LocationListener{
	private static final String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";   
	private WebView webView;
	private Location mostRecentLocation=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		          
	    getLocation();
	    setupWebView();
	    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	private void getLocation() {   
	    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);   
	    Criteria criteria = new Criteria();   
	    criteria.setAccuracy(Criteria.ACCURACY_FINE);   
//	    String provider = locationManager.getBestProvider(criteria,true);
	    String provider =LocationManager.GPS_PROVIDER;
	    //In order to make sure the device is getting the location, request updates. 
	    
	    locationManager.requestLocationUpdates(provider, 1000, 10, this);   
	    mostRecentLocation = locationManager.getLastKnownLocation(provider);   
	    
	  }
//	@SuppressLint("SetJavaScriptEnabled") @JavascriptInterface
	private void setupWebView(){ 
//		  final String centerURL = "javascript:centerAt(" + 
//	                               "39.904214" + "," + 
//				                   "116.40741300000002"+ ")"; 
		final String centerURL = "javascript:centerAt(" +   
			    mostRecentLocation.getLatitude() + "," +   
			    mostRecentLocation.getLongitude()+ ")"; 
		  webView = (WebView) findViewById(R.id.webview); 
		  webView.getSettings().setJavaScriptEnabled(true); 
		  //Wait for the page to load then send the location information
		  webView.setWebViewClient(new WebViewClient(){   
			    @Override   
			    public void onPageFinished(WebView view, String url){   
			      webView.loadUrl(centerURL);   
			    }   
			  });
		  webView.loadUrl("file:///android_asset/map.html");//使用自己自定义布局的webmap页面
//		  webView.loadUrl(MAP_URL);//用的谷歌的webmap例子支持页面
		  /** Allows JavaScript calls to access application resources **/ 
//		  webView.addJavascriptInterface(new JavaScriptInterface(), "android");//一些手机不支持js 
		} 
		/** Sets up the interface for getting access to Latitude and Longitude data from device 
		 **/ 
		private class JavaScriptInterface { 
//		  public double getLatitude(){ 
//		    return 39.904214; 
//		  } 
//		  public double getLongitude(){ 
//		    return 116.40741300000002; 
//		  } 
			public double getLatitude(){   
			    return mostRecentLocation.getLatitude();   
			  }   
			  public double getLongitude(){   
			    return mostRecentLocation.getLongitude();   
			  }
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.menu_settings) {
			String centerNow = "javascript:centerAt(39.904214,116.40741300000002);";
			webView.loadUrl(centerNow);
			return true;
		}
		else if(id == R.id.menu_search){		
			String search = "javascript:calcRoute('北京','上海','TRANSIT');";
			webView.loadUrl(search);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	private long waitTime = 2000;  
	private long touchTime = 0; 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
    	
		return super.onKeyDown(keyCode, event);
	}

}

这就是个完整的代码!主要点在setupWebView()函数里:

这一句:webView.loadUrl(centerURL)表示我调用map.html里的js函数:function centerAt(latitude, longitude)!

而这句话:webView.loadUrl("file:///android_asset/map.html");是加载我的map.html文件!当然你也可以直接加载你自己做好的在线web页面!你保证是可以访问到就行!

整个调用就这么简单的完成了!不上图了,这些我觉得已经足够了吧!运行就行!



版权声明:本文为hhp5127447原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。