添加搜索按钮以映射

时间:2015-11-04 15:05:33

标签: android xml google-maps android-studio google-maps-android-api-2

我正在尝试向android地图添加搜索栏。 地图将作为片段之一添加到项目中。该错误似乎由this引入。任何帮助表示赞赏。提前谢谢。

public class Maps extends Fragment {
    //Initial code

   public void onSearch(View view) {
        EditText location_tf = (EditText) getView().findViewById(R.id.TFaddress);
        String location = location_tf.getText().toString();
        List < Address > addressList = null;

        if (location != null || !location.equals(""))
        Geocoder geocoder = new Geocoder(this);

        try {
            addressList = geocoder.getFromLocationName(location, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Address address = addressList.get(0);
    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}

的xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <EditText android:layout_width="287dp"
            android:layout_height="wrap_content"
            android:id="@+id/TFaddress"/>
        <Button style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"
            android:text="Search"
            android:id="@+id/button"
            android:layout_gravity="right"
            android:onClick="onSearch" />
        <com.google.android.gms.maps.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>

错误:

Error:(83, 46) error: incompatible types: MAPS cannot be converted to Context
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output.    
Error:Execution failed for task ':app:compileDebugJava'. Compilation failed; see the compiler error output for details.

1 个答案:

答案 0 :(得分:0)

根据the documentationGeocoder构造函数需要Context,而不是Fragment,所以此行

Geocoder geocoder = new Geocoder(this);

应该是

Geocoder geocoder = new Geocoder(getActivity());

另外,请考虑您可能需要在if声明中添加括号:

if (location != null || !location.equals(""))
    Geocoder geocoder = new Geocoder(this);

    try {
        addressList = geocoder.getFromLocationName(location, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
}