Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/182.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将附近位置的数据获取到Listview中?_Java_Android_Google Maps_Listview_Google Nearby - Fatal编程技术网

Java 如何将附近位置的数据获取到Listview中?

Java 如何将附近位置的数据获取到Listview中?,java,android,google-maps,listview,google-nearby,Java,Android,Google Maps,Listview,Google Nearby,我必须在代码中包含哪些方法才能将数据传递到列表视图? 我想用ListView显示附近的地方。它仅通过单击如下所示的按钮在地图上显示附近的位置。当我单击“附近学校”按钮时,它会在地图上显示附近的学校,现在我希望它使用listview显示附近的学校。我该怎么做 public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, OnMapRead

我必须在代码中包含哪些方法才能将数据传递到列表视图? 我想用ListView显示附近的地方。它仅通过单击如下所示的按钮在地图上显示附近的位置。当我单击“附近学校”按钮时,它会在地图上显示附近的学校,现在我希望它使用listview显示附近的学校。我该怎么做

public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
ListView lvMap;

ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.maps);
    mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);



    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Restaurant = "restaurant";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Restaurant);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
        }
    });

    Button btnHospital = (Button) findViewById(R.id.btnHospital);
    btnHospital.setOnClickListener(new View.OnClickListener() {
        String Hospital = "hospital";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Hospital);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Hospitals", Toast.LENGTH_LONG).show();
        }
    });

    Button btnSchool = (Button) findViewById(R.id.btnSchool);
    btnSchool.setOnClickListener(new View.OnClickListener() {
        String School = "school";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }
            String url = getUrl(latitude, longitude, School);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Schools", Toast.LENGTH_LONG).show();
        }
    });
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + latitude + "," + longitude);
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
    googlePlacesUrl.append("&type=" + nearbyPlace);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}
}
公共类MapsActivity扩展了FragmentActivity实现com.google.android.gms.location.LocationListener、OnMapReadyCallback、GoogleAppClient.ConnectionCallbacks、,
GoogleAppClient.OnConnectionFailedListener{
私有谷歌地图;
双纬度;
双经度;
私人int近距离_半径=10000;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
位置请求mLocationRequest;
列表视图lvMap;
ArrayList placesListItems=新的ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
//检查Google Play服务是否可用
如果(!CheckGooglePlayServices()){
Log.d(“onCreate”,“由于Google Play服务不可用,正在完成测试用例”);
完成();
}
否则{
Log.d(“onCreate”,“Google Play服务可用”);
}
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.maps);
getMapAsync(这个);
}
私有布尔值CheckGooglePlayServices(){
GoogleAppAvailability googleAPI=GoogleAppAvailability.getInstance();
int result=googleAPI.isGooglePlayServicesAvailable(此);
if(result!=ConnectionResult.SUCCESS){
if(googleAPI.isUserResolvableError(result)){
googleAPI.getErrorDialog(这个,结果,
0)show();
}
返回false;
}
返回true;
}
/**
*一旦可用,就可以操纵贴图。
*当映射准备好使用时,将触发此回调。
*这是我们可以添加标记或线条、添加侦听器或移动摄影机的地方。在这种情况下,
*我们只是在澳大利亚悉尼附近加了一个标记。
*如果设备上未安装Google Play服务,系统将提示用户安装
*它位于SupportMapFragment内。此方法仅在用户
*已安装Google Play服务并返回应用程序。
*/
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
mMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
//初始化Google Play服务
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
}
否则{
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
按钮btnRestaurant=(按钮)findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(新视图.OnClickListener(){
String Restaurant=“Restaurant”;
@凌驾
公共void onClick(视图v){
Log.d(“onClick”,“单击按钮”);
mMap.clear();
字符串url=getUrl(纬度、经度、餐厅);
对象[]数据传输=新对象[2];
数据传输[0]=mMap;
DataTransfer[1]=url;
Log.d(“onClick”,url);
GetNearbyPlacesData GetNearbyPlacesData=新建GetNearbyPlacesData();
执行(数据传输);
Toast.makeText(MapsActivity.this,“附近的餐馆”,Toast.LENGTH_LONG.show();
}
});
按钮btnHospital=(按钮)findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(新视图.OnClickListener(){
String Hospital=“Hospital”;
@凌驾
公共void onClick(视图v){
Log.d(“onClick”,“单击按钮”);
mMap.clear();
字符串url=getUrl(纬度、经度、医院);
对象[]数据传输=新对象[2];
数据传输[0]=mMap;
DataTransfer[1]=url;
Log.d(“onClick”,url);
GetNearbyPlacesData GetNearbyPlacesData=新建GetNearbyPlacesData();
执行(数据传输);
Toast.makeText(MapsActivity.this,“附近的医院”,Toast.LENGTH_LONG.show();
}
});
按钮btnSchool=(按钮)findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(新视图.OnClickListener(){
字符串School=“School”;
@凌驾
公共void onClick(视图v){
Log.d(“onClick”,“单击按钮”);
mMap.clear();
if(mCurrLocationMarker!=null){
mCurrLocationMarker.remove();
}
字符串url=getUrl(纬度、经度、学校);
对象[]数据传输=新对象[2];
数据传输[0]=mMap;
DataTransfer[1]=url;
Log.d(“onClick”,url);
GetNearbyPlacesData GetNearbyPlacesData=新建GetNearbyPlacesData();
执行(数据传输);
Toast.makeText(MapsActivity.this,“附近的学校”,Toast.LENGTH_LONG.show();
}
});
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
未连接的公共空间(捆绑包){