开发者

google maps overlay

开发者 https://www.devze.com 2023-04-02 20:47 出处:网络
I was using this code to overlay my position on Google maps using GPS this code was working when I have Android 3.1 but when the operating system up graded to 3.2 it stop woking and force close error

I was using this code to overlay my position on Google maps using GPS this code was working when I have Android 3.1 but when the operating system up graded to 3.2 it stop woking and force close error comes out at the end.

This file is position overlay

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class MyPositionOverlay extends Overlay {

  private final int mRadius = 5;

  Location location;

  public Location getLocation() {
    return location;
  }
  public void setLocation(Location location) {
    this.location = location;
  }

  @Override
  public boolean onTap(GeoPoint point, MapView mapView) {
    return false;
  }

  @Override
  public void draw(Canvas canvas, MapView mapView, boolean shadow) {
    Projection projection = mapView.getProjection();

    if (shadow == false) {
      // Get the current location    
      Double latitude = location.getLatitude()*1E6;
      Double longitude = location.getLongitude()*1E6;
      GeoPoint geoPoint; 
      geoPoint = new 
        GeoPoint(latitude.intValue(),longitude.intValue());

      // Convert the location to screen pixels     
      Point point = new Point();
      projection.toPixels(geoPoint, point);

      RectF oval = new RectF(point.x - mRadius, point.y - mRadius, 
                             point.x + mRadius, point.y + mRadius);

      // Setup the paint
      Paint paint = new Paint();
      paint.setARGB(250, 255, 255, 255);
      paint.setAntiAlias(true);
      paint.setFakeBoldText(true);

      Paint backPaint = new Paint();
      backPaint.setARGB(175, 50, 50, 50);
      backPaint.setAntiAlias(true);

      RectF backRect = new RectF(point.x + 2 + mRadius, 
                                 point.y - 3*mRadius,
                                 point.x + 65, point.y + mRadius);

      // Draw the marker    
      canvas.drawOval(oval, paint);
      canvas.drawRoundRect(backRect, 5, 5, backPaint);
      canvas.drawText("Here I Am", 
                      point.x + 2*mRadius, point.y, 
                      paint);
    }
    super.draw(canvas, mapView, shadow);
  }
}

this is the main file

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

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class WhereAmI extends MapActivity {
  @Override
  protected boolean isRouteDisplayed() {
    return false;
  }

  MapController mapController;
  MyPositionOverlay positionOverlay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MapView myMapView = (MapView)findViewById(R.id.myMapView);
    mapController = myMapView.getController();

    myMapView.setSatellite(true);
    myMapView.setStreetView(true);
    myMapView.displayZoomControls(false);

    mapController.setZoom(17);

    // Add the MyPositionOverlay
    positionOverlay = new MyPositionOverlay();
    List<Overlay> overlays = myMapView.getOverlays();
    overlays.add(positionOverlay);

    LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);

    updateWithNewLocation(location);

    locationManager.requestLocationUpdates(provider, 2000, 10,   
                                           locationListener);
  }

  private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status, 
                                Bundle extras){ }
  };

  private void updateWithNewLocation(Location location) {
    String latLongString;
    TextView myLocationText;
    myLocationText = (TextView)findViewById(R.id.myLocationText);
    String addressString = "No address found";

    if (location != null) {
         // Update my location marker
        positionOverlay.setLocation(location);

      // Update the map location.
      Double geoLat = location.getLatitude()*1E6;
      Double geoLng = location.getLongitude()*1E6;
      GeoPoint point = new GeoPoint(geoLat.intValue(), 
                                    geoLng.intValue());

      mapController.animateTo(point);

      double lat = location.getLatitude();
      double lng = location.getLongitude();
      latLongString = "Lat:" + lat + "\nLong:" + lng;

      double latitude = location.getLatitude();
      double longitude = location.getLongitude();

      Geocoder gc = new Geocoder(this, Locale.getDefault());
      try {
        List<Address> addresses = gc.getFromLocation(latitude, 
                                                     longitude, 1);
        StringBuilder sb = new StringBuilder();
        if (addresses.size() > 0) {
          Address address = addresses.get(0);

          for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
            sb.append(address.getAddressLine(i)).append("\n");

            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
        }
        addressString = sb.toString();
      } catch (IOException e) {}
    } else {
      latLongString = "No location found";
    }
    myLocationText.setText("Your Current Position is:\n" + 
                            latLongString + "\n" + addressString);
  }
}

for xml

<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:id="@+id/myLocationText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
  />
  <com.google.android.maps.MapView
    android:id="@+id/myMapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:enabled="true"
    android:clickable="true"
    android:apiKey="0LSm5iUqsTW3O-7e74GQTt4pQKnxW7YVu-3Cftg"
  />
</LinearLayout>

logcat output error are

09-07 13:33:43.180: ERROR/AndroidRuntime(1811): FATAL EXCEPTION: main
09-07 13:33:43.180: ERROR/AndroidRuntime(1811): java.lang.NullPointerException
09-07 13:3开发者_运维技巧3:43.180: ERROR/AndroidRuntime(1811):     at com.paad.whereami.MyPositionOverlay.draw(MyPositionOverlay.java:37)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.google.android.maps.Overlay.draw(Overlay.java:179)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:45)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.google.android.maps.MapView.onDraw(MapView.java:530)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.View.draw(View.java:9279)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.drawChild(ViewGroup.java:2584)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.drawChild(ViewGroup.java:2582)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.drawChild(ViewGroup.java:2582)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.drawChild(ViewGroup.java:2582)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2189)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.View.draw(View.java:9282)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.widget.FrameLayout.draw(FrameLayout.java:419)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1923)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewRoot.draw(ViewRoot.java:1695)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1410)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.view.ViewRoot.handleMessage(ViewRoot.java:2040)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.os.Looper.loop(Looper.java:132)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at android.app.ActivityThread.main(ActivityThread.java:4123)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at java.lang.reflect.Method.invokeNative(Native Method)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at java.lang.reflect.Method.invoke(Method.java:491)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
09-07 13:33:43.180: ERROR/AndroidRuntime(1811):     at dalvik.system.NativeStart.main(Native Method)


I doubt that it's the OS version that causes the null pointer. More likely it's because you 'location' in the overlay class is null when draw gets called.

In the draw method replace

if (shadow == false) {

with

if ((shadow == false) && (location != null)) {
0

精彩评论

暂无评论...
验证码 换一张
取 消