1

私が作成しているアプリケーションの一部には、グーグルマップが必要です。ユーザーが編集テキストに検索文字列を入力してから検索ボタンを押すと、マップが最初の結果にアニメーション化されるようにしたいと思います。

ボタンを押すと、アプリケーションは最初の結果を検索して取得し、それをジオポイントに配置します。これにより、プログラムの一部が機能します。しかし、その時点までアニメーション化しようとすると、アプリケーションがクラッシュします。

これが、「アイスランドのダルビーク」という場所に正常に移動したonCreate関数です。

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();

    }

そして、ボタンクリックの私のコードはです。明確にするために、System.out.println(point)は有効なポイントを出力します。しかし、それでもボタンをクリックすると、アプリケーションがクラッシュします。

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();
        }   
    }

また、searchLocation関数は次のとおりです。

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;
        }   
}

したがって、要約するために、onclickの「検索」機能で明らかに何か間違ったことをしています。

何が悪いのか考えてみませんか?

4

2 に答える 2

0

正しい変数のnull値をチェックしていません:

    if( point != null){
        mc.animateTo(tmpPoint);
        mapView.invalidate();
    }   

する必要があります

    if( tmpPoint!= null){
        mc.animateTo(tmpPoint);
        mapView.invalidate();
    }   

さらに、geoCoder.getFromLocationName時間がかかる可能性があるため、UIスレッドの外部でメソッドを呼び出す必要があります。AsyncTaskたとえば、そのためにを使用します。

最後に、住所のリストを取得しても、緯度と経度が保証されているわけではありません。hasLatitudeand関数を使用してhasLongitude、座標を含む結果リストの最初のアドレスを選択します。

于 2012-11-17T12:00:39.240 に答える
0

私は答えを見つけました。

これを引き起こした問題はこの行でした

mapView.invalidate();

于 2012-11-17T15:47:18.900 に答える