Android google maps WebView example with Geocoding to get Latitude and Longitude

Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.

Android google maps WebView example
Before you start coding the Android application, you must setup a html page using Google Maps JavaScript API on a web server of your choice. Then you can reference the html page in your android application WebView. The example here uses an ArrayAdapter to list Countries. When you click on a given country, it uses that to Geocode its latitude and longitude. After that it centers the map to that location with the specifies zoom level. The user can then use the Maps control to zoom in and out, also can navigate using touch gestures.

Source for androidMap.html to be deployed on your Web Server

<!DOCTYPE html>
<html> 
<head> 
<title>Google Maps JavaScript API v3 Example: Overlay Removal</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var map;
  var markersArray = [];

  function initialize() {
    var haightAshbury = new google.maps.LatLng(0,0);
    var mapOptions = {
      zoom: 5,
      center: haightAshbury,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);

    google.maps.event.addListener(map, 'click', function(event) {
      addMarker(event.latLng);
    });
  }
  
  function centerAt(latitude, longitude){
        myLatlng = new google.maps.LatLng(latitude,longitude);
        map.panTo(myLatlng);
        addMarker(myLatlng);
  }       
  
  function addMarker(location) {
    clearOverlays(); 
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markersArray.push(marker);
  }

 // Removes the overlays from the map, but keeps them in the array
  function clearOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
    }
  }

  // Shows any overlays currently in the array
  function showOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(map);
      }
    }
  }

  // Deletes all markers in the array by removing references to them
  function deleteOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }
</script> 
</head> 
<body onload="initialize();"> 
<!--
  <div>
     <input onclick="clearOverlays();" type=button value="Clear Overlays"/>
    <input onclick="showOverlays();" type=button value="Show All Overlays"/>
    <input onclick="deleteOverlays();" type=button value="Delete Overlays"/> 
  </div> 
--> 
  <div id="map_canvas"></div> 
</body> 
</html> 

Source for GoogleMapsWebViewActivity.java

package com.as400samplecode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class GoogleMapsWebViewActivity extends Activity {

    private ListView mListView;
    private WebView mapView;
    private ArrayList<String> myAddressList = new ArrayList<String>();
    private String myAddress;
    private String centerURL;;

    static final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
        "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
        "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
        "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
        "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
        "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
        "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
        "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
        "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
        "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
        "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
        "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
        "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
        "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
        "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
        "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
        "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
        "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
        "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
        "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
        "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
        "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
        "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
        "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
        "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
        "Ukraine", "United Arab Emirates", "United Kingdom",
        "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
        "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
        "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mListView = (ListView) findViewById(R.id.listView1);
        mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES));

        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // When clicked, show a toast with the TextView text
                Log.v("GoogleMapsWebViewActivity:", "Country: " + ((TextView) view).getText().toString());
                myAddressList.clear();
                String thisAddress = ((TextView) view).getText().toString();
                myAddressList.add(thisAddress);
                myAddress = thisAddress;
                //Set Map
                mapCustomerAddress();
            }
        });

        Button submit = (Button) findViewById(R.id.showMap);
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Uri uri = Uri.parse("geo:0,0?q=" + myAddress);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

            }
        });

    }

    private void mapCustomerAddress(){

        boolean internet =  isNetworkAvailable(GoogleMapsWebViewActivity.this);
        if(internet){
            Button mapButton = (Button) findViewById(R.id.showMap);
            mapButton.setEnabled(true);

            //getLocation();
            Log.v("GoogleMapsWebViewActivity:", "Address Size: " + myAddressList.size());
            Geocoder geoCoder = new Geocoder(GoogleMapsWebViewActivity.this, Locale.getDefault());   
            List<Address> addresses= null;
            try {
                for(int i=0;i<myAddressList.size();i++){
                    addresses = geoCoder.getFromLocationName(myAddressList.get(i), 5);
                    if(addresses.size() >0){
                        myAddress = myAddressList.get(i);
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            setupWebView(addresses);
        }
        else {
            Button mapButton = (Button) findViewById(R.id.showMap);
            mapButton.setEnabled(false);

            mapView = (WebView) findViewById(R.id.mapView);
            String mapNotAvailable =     "<html><head></head><body>" +
            "<img src='map_not_available.png' width='100%'/>" +
            "<br/><b>You need internet connectivity for Maps!</b>" +
            "</body><html>";
            mapView.loadDataWithBaseURL("file:///android_asset/", mapNotAvailable, "text/html", "utf-8", null);

        }

    }

    /** Sets up the WebView object and loads the URL of the page **/
    private void setupWebView(List<Address> addresses){
        Log.v("GoogleMapsWebViewActivity:", "Address Size: " + addresses.size());
       
        if (addresses.size() > 0) {
            Log.v("GoogleMapsWebViewActivity:", "Address Lat: " + addresses.get(0).getLatitude());
            Log.v("GoogleMapsWebViewActivity:", "Address Long: " + addresses.get(0).getLongitude());

            centerURL = "javascript:centerAt(" + 
            addresses.get(0).getLatitude() + "," + 
            addresses.get(0).getLongitude()+ ")";
        }   

        mapView = (WebView) findViewById(R.id.mapView);
        mapView.getSettings().setJavaScriptEnabled(true);
        //Wait for the page to load then send the location information
        mapView.setWebViewClient(new WebViewClient(){ 
            @Override 
            public void onPageFinished(WebView view, String url) 
            {
                mapView.loadUrl(centerURL);
            }

        });
        String MAP_URL = "http://10.0.2.2:8080/CapitalWebServices/androidMap.html";
        mapView.loadUrl(MAP_URL); 
    }

    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    Log.v("INTERNET:",String.valueOf(i));
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.v("INTERNET:", "connected!");
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

Source for list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textSize="25sp" android:textStyle="bold" />
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" 
  android:id="@+id/linearLayout1" android:orientation="horizontal">
        <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout2"
            android:orientation="vertical" android:layout_weight="30" android:layout_width="0dp">
            <ListView android:id="@+id/listView1" android:layout_height="wrap_content"
                android:layout_width="match_parent" />
        </LinearLayout>
        <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout3"
            android:orientation="vertical" android:layout_weight="70" android:layout_width="0dp">
            <Button android:text="View Larger Map and Get Directions" 
   android:id="@+id/showMap" android:layout_height="wrap_content" 
   android:layout_width="match_parent">
   </Button>
            <WebView android:id="@+id/mapView" android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.as400samplecode"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
       
    <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light">
        <activity android:name=".GoogleMapsWebViewActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.