Search code examples
androidandroid-mapviewgeopoints

Can't animate to a valid geopoint on button click


One part of the application I am making requires google map. I want the user to be able to type into edittext some search string and then press a search button and the map will animate to the first result.

When I press the button the application searches and takes the first result and puts it into a geopoint, so that part of the program is working. But when I try to animate to that point the application crashes.

Here is the onCreate function where I successfully navigate to the location "Dalvík, Iceland".

public class LocationPicker extends MapActivity {
    static GeoPoint point;
    static MapController mc;
    static MapView mapView;
    private EditText location;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_picker);
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        location = (EditText)findViewById(R.id.locationString);
        mc = mapView.getController();
        String tmp = "Dalvík, Iceland";
        try {
            point = searchLocation(tmp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mc.animateTo(point);
        mc.setZoom(14); 
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);   

        mapView.invalidate();

    }

And my code for the button click is, and to be clear the System.out.println(point) prints valid point. But still when I click the button my application crashes.

public void search(View v) throws IOException{
        GeoPoint tmpPoint = searchLocation(location.getText().toString());
        System.out.println(tmpPoint);
        if( tmpPoint != null){
            mc.animateTo(tmpPoint);
            mapView.invalidate();
        }   
    }

And the searchLocation functions is as follows:

public GeoPoint searchLocation (String searchString) throws IOException{
        Geocoder geo = new Geocoder(this);
        List<Address> addr;
        addr = geo.getFromLocationName(searchString, 10);
        if(!addr.isEmpty()){
                    Address loc = addr.get(0);
                    GeoPoint point = new GeoPoint((int) (loc.getLatitude() * 1E6),
                        (int) (loc.getLongitude() * 1E6));
                    return point;
        }
        else {  
            return null;
        }   
}

So to summerize I am clearly doing something wrong in the onclick "search" function.

Any ideas what is wrong?


Solution

  • I found the answer.

    The problem causing this was this line

    mapView.invalidate();