tags:

views:

1379

answers:

3

I have the following code but the lon/lat seems to be returning null;

package com.domain.www;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Criteria;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebMapActivity extends Activity implements LocationListener {

    private static final String MAP_URL = "http://www.yahoo.com/";
    private WebView webView;
    private Location mostRecentLocation;

    @Override
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            getLocation();
            setupWebView();
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /** Sets up the WebView object and loads the URL of the page **/
    private void setupWebView() {
        /*
            final String centerURL = "javascript:centerAt("
                    + mostRecentLocation.getLatitude() + ","
                    + mostRecentLocation.getLongitude() + ")"; */

            webView = (WebView) findViewById(R.id.webview);
            webView.getSettings().setJavaScriptEnabled(true);

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url)
                {
                    String jsCode = "javascript:alert('" + getMostRecentLocation("lon") + "')";
                    webView.loadUrl(jsCode.toString());
                }
            });


            webView.loadUrl(MAP_URL);
    }

    /**
     * The Location Manager manages location providers. This code searches for
     * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
     * mechanism) and finds the last known location.
     **/
    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);

        // In order to make sure the device is getting location, request
        // updates. locationManager.requestLocationUpdates(provider, 1, 0,
        // this);
        //locationManager.requestLocationUpdates(provider, 1, 0, this);
        setMostRecentLocation(locationManager.getLastKnownLocation(provider));
    }

    /** Sets the mostRecentLocation object to the current location of the device **/
    @Override
    public void onLocationChanged(Location location) {
        setMostRecentLocation(location);
    }

    /**
     * The following methods are only necessary because WebMapActivity
     * implements LocationListener
     **/
    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    /**
     * @param mostRecentLocation the mostRecentLocation to set
     */
    public void setMostRecentLocation(Location mostRecentLocation) {
        this.mostRecentLocation = mostRecentLocation;
    }

    /**
     * @return the mostRecentLocation
     */
    public double getMostRecentLocation(String lonLat) {
        double gValue = 0.00;
        try
        {
        Location xx = this.mostRecentLocation;  //Used as a breakpoint
        if(lonLat == "lat") gValue = this.mostRecentLocation.getLatitude();
        if(lonLat == "lon") gValue = this.mostRecentLocation.getLongitude();        

        } catch (Exception e) {
            e.printStackTrace();
        }

        return gValue;  
    }

}

Ignore the URL bit that would be a page with a google map on it; but for debugging purposes I'd prefer it to just spit out an alert with the values in it.

Any ideas whats wrong? Target Emulators (Google API 1.5 API(3))

Thanks

+2  A: 

You probably want to use WebView#addJavascriptInterface instead of loading javascript: URLs, as it'll be much cleaner.

Basically what you'll want to do is:

  1. Create a class that has a method which returns location data.
  2. Create an instance of the class and pass it to WebView using addJavascriptInterface (here you'll provide a global variable name to use in Javascript).
  3. From the Javascript in the page, call the method on the global variable defined by addJavascriptInterface, and use the results as you'd like.

Fore more, see this question on Stack Overflow.

Roman Nurik
Ta; the main issue at the moment though isnt code syntax for the JS but that getLocation is returning 0.0 (the default value) rather then a long lat in debug. setMostRecentLocation(locationManager.getLastKnownLocation(provider));
HappyGuy
+5  A: 

The reason for the 0,0 latitude and longitude is that you don't have a latitude or longitude. You have done nothing in your code to get a location -- getLastKnownLocation() only works if there is something else in your code requesting location updates.

Here is a sample project that does what you want, either by pulling (a la Mr. Nurik's addJavascriptInterface() recommendation), or by pushing (using the javascript: notation).

CommonsWare
Ah Cock. Explains why it was null *forehead slap*Thanks again dude :o)
HappyGuy
A: 

If location is null

If getLastKnownLocation or getLastKnownBestLocation returns null then you should consider changing your build target from 'Android 1.5' to 'Google API 1.5'. That solved the issue for me.

You can change the Build Target for your project any time in Eclipse: Right-click the project in Package Explorer, select Properties > Android and then check 'Google API' for Project Target.

-

If location is 0.0

If getLastKnownLocation returns 0.0 after pressing the 'Send' button in DDMS' Location Controls, you probably are working with non-English culture settings. It's an emulator bug fixed with the upcoming release 7 of the SDK tools; for a quick fix you can change your locale to 'en'. (See http://code.google.com/p/android/issues/detail?id=915 for details.)

Reading your comment to Roman Nurik I think the SDK bug with non-English culture settings is troubling you. Change your language settings in Eclipse or your OS and you'll be fine. As an alternative to that you can use a telnet session to send a longitude and latitude.

telnet localhost:5554
geo fix 52.383144 5.217133
Patrick de Kleijn
At second thought, this had nothing to do with chosen API or your language settings. (... as you are located in London. :-) Anyhow, might be useful to others having similar symptoms with getLocation returning null or 0.0.
Patrick de Kleijn