Monday, May 7, 2012

Android - Google Maps inside an App


In AndroidManifest.xml
------------------------
<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" />


In the Java code for the activity
---------------------------------
add "implements LocationListener" to the defination of the class


String MapUrl = "http://www.google.com/maps?q=37.423156,-122.084917";

//MapUrl = "http://maps.google.com/maps?q=Pizza,texas&ui=maps";

private WebView _webView;

_webView = (WebView)_yourrelativelayourSrc.findViewById(R.id.layout_webview);

_webView.getSettings().setJavaScriptEnabled(true);
_webView.getSettings().setBuiltInZoomControls(true);
_webView.getSettings().setSupportZoom(true);

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria,true);
//In order to make sure the device is getting the location, request updates.
locationManager.requestLocationUpdates(provider, 1, 0, this);
mostRecentLocation = locationManager.getLastKnownLocation(provider);

MapUrl = "http://www.google.com/maps?q=" + mostRecentLocation.getLatitude().toString() + "," +
 mostRecentLocation.getLongitude().toString();

final String centerURL = "javascript:centerAt(" +  mostRecentLocation.getLatitude() + "," +
  mostRecentLocation.getLongitude()+ ")";

_webView.setWebChromeClient(new WebChromeClient()
{
     public void onProgressChanged(WebView view, int progress)
     {
            // Activities and WebViews measure progress with different scales.
            // The progress meter will automatically disappear when we reach 100%
            ((Activity) activity).setProgress(progress * 1000);
     }

});

//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(MapUrl);