Monday 15 October 2012

Using Google Street View in Android Applications

Street View is a nice feature Google have created for us to see street level images of our current position or specified location... you can find more information on getting your current location in this post.

Using street view in android applications can be accomplished in a number of ways depending on the final objective.  The two ways I'm going to explain here is 1. Using Street View Intent and 2. Using Street View inside an embedded Web View.  There are benefits to each of these methods but each will have their drawbacks and limitations when you start to explore further.

1. Using Street View Intent

The street view intent is the quick and easy way to see a location at street level with the minimal code and effort. The following intent will launch the street view application installed on the android device and go the the desired location:
In my specific code I add try / catch around the startActivity() in case there is errors loading the street view application. 
                Uri streetViewUri = Uri.parse(
                        "google.streetview:cbll=" + geoLocation + "&cbp=1,90,,0,1.0&mz=20");
                Intent streetViewIntent = new Intent(Intent.ACTION_VIEW, streetViewUri);
                startActivity(streetViewIntent);

where "geoLocation" is the longitude and latitude co-ordinates of the location you would like to see such as "51.5271124,-0.1337308" .

Full details on all parameters required and what can be included in the intent are available at Invoking Google Applications on Android Devices .

One drawback of using this may be that the street view application is not installed on the device by default so either installing it or detecting it with PackageManager / queryIntentActivites() will help resolve.

                 try {
                    startActivity(streetViewIntent);
                } catch (Exception e) {
                    Toast toast = Toast.makeText(getApplicationContext(), "Error Loading StreetView ",
                            Toast.LENGTH_SHORT);
                    toast.show();
                }

There will be cases where there is no street view for the specified location and an empty white page will be seen so you may have to do some magic with Google's api to check if street view is available for that location first.

If you want to start doing any thing fancy using street view, maybe displaying a marker for the location or even multiple markers with a custom image. This way you have to then start looking at using a web view and Google Street View Service ..... 

2. Using Street View inside an embedded Web View.

Google Street View Service contains full documentation on how to customise your street view in any webview with custom html code. In this explanation I am going to explain how to get set up for this in an android application.

Firstly create a standard activity with basic xml layout, including a webview

Configure settings for the webview as follows:

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

You will then need to create some custom html code that will be loaded into this view. You can come up with many different combinations and examples from reading the Street View Api  however below is a basic example that will load street view at your current or specified location with a custom marker for a place:


String htmlCode = "

<html>
  <head>
    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Street View Layer</title>
    <link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
      var panorama;

      function initialize() {

        var myLocation = new google.maps.LatLng(51.5271124,-0.1337308);
        var panoramaOptions = {
          position: myLocation,
        };

        panorama = new  google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);


        var stationMarker = new google.maps.MarkerImage('http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Underground.svg/500px-Underground.svg.png');

        var station = new google.maps.Marker({
        position: new google.maps.LatLng(51.5274683,-0.1345183),
        map: panorama,
        icon: stationMarker,
        title: 'Euston Station',
       });
      }

    </script>

  </head>
  <body onload="initialize()">
    <div id="pano" style='width:100%; height:100%; padding:0; margin:0; -webkit-user-modify: read-write-plaintext-only; -webkit-tap-highlight-color:rgba(0,0,0,0)'></div>
  </body>
</html>  "

The above code firstly ensure we are using street view and positioned at "myLocation". Then we create a custom marker name "stationMarker" using an image from a custom url and display this at the new postion (51.5274683,-0.1345183).


The bottom code is some custom styling to make the street view look more appealing on the android device. 


You can also play around with the string and replace the long / lat ordinates with your own location like below:


"        var myLocation = new google.maps.LatLng(" + myLocation +");"


Any manipulation and substitution can be done here to get custom data into the html string. In my own example app I plot multiple overlays just by replicating the "stationMarker" section and setting new positions.  


The final pieces of code required are:


        webView.loadData(htmlCode, "text/html", "UTF-8");

        webView.setWebViewClient(new MyWebViewClient()); 

The MyWebViewClient class will allow you to load the html into your own webview rather than launching the default browser or selection dialog:



    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

Using street view in a webview by specifying custom html code is more flexible in what you can do and show, however things can get very complex if your not too familiar with the simple html / java script coding. Even the tiniest mistake or missing character will cause the html code to break. 

To help: One thing that I found easier is test the html string in a live online code tester such as http://htmledit.squarefree.com/ first, this will save modifying your app and running the android application over and over again!

No comments:

Post a Comment