设置当前位置到位自动完成片段 [英] Set Current Place in Place Autocomplete Fragment

查看:58
本文介绍了设置当前位置到位自动完成片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在创建活动时将当前地点设置为地点自动完成片段.

I want to set the current place into the place autocomplete fragment when the activity is created.

我能够加载Google Maps API,并且已经在我的应用程序中成功实现了Place Autocomplete Fragment.但是,我希望场所自动完成片段将当前场所设置为场所自动完成片段的默认字符串.就像Uber一样.当我们打开Uber并单击编辑文本时说:去哪儿?"它要求我们输入或搜索目的地位置,并自动将位置设置为当前位置.我的代码如下:

I am able to Load Google Maps API and I have successfully implemented Place Autocomplete Fragment in my application. But, I want place autocomplete fragment to set the current place as default string in place autocomplete fragment. Just like Uber does. When we open Uber and click on the edit text saying "Where to?" it ask us to enter or search for destination location and it automatically set the location to the current place. My code is given below:

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceDetectionApi;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.Arrays;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private static final int REQUEST_SEND_SMS = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    try {
        // Customise the styling of the base map using a JSON object defined
        // in a raw resource file.
        boolean success = mMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(
                        this, R.raw.aubergine_maps_style_json));

        if (!success) {
            Log.e("MapsActivityRaw", "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e("MapsActivityRaw", "Can't find style.", e);
    }

    // Add a marker in Sydney and move the camera
    /* LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); */
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    if(Build.VERSION.SDK_INT >=23){
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            } else {
                if (shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_FINE_LOCATION) || shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                }
                requestPermissions(new String[]{
                        android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION
                }, REQUEST_SEND_SMS);
            }
        }
    }

    Location location = getLastKnownLocation();

    if (location != null)
    {
        this.mMap.getUiSettings().setMyLocationButtonEnabled(false);
        this.mMap.setMyLocationEnabled(true);

        GPSTracker tracker = new GPSTracker(this);
        double latitude = 0;
        double longitude = 0;
        if (!tracker.canGetLocation()) {
            tracker.showSettingsAlert();
        } else {
            latitude = tracker.getLatitude();
            longitude = tracker.getLongitude();
        }

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
    } else {
        Toast.makeText(getApplicationContext(), "Location Is Null", Toast.LENGTH_LONG).show();
    }

    PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setText("");

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            System.out.println("Place Name: " + place.getName());
            System.out.println("Place ID: " + place.getId());
            System.out.println("Place Address: " + place.getAddress());
            System.out.println("Place LatLng: " + place.getLatLng());
            String latLng = place.getLatLng().toString();
            latLng = latLng.replace("lat/lng: (", "");
            latLng = latLng.replace(")","");
            String[] latLngArray = latLng.split(",");
            System.out.println("Latitude Only: " + latLngArray[0]);
            System.out.println("Longitude Only: " + latLngArray[1]);

            mMap.clear();

            mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(Double.parseDouble(latLngArray[0]), Double.parseDouble(latLngArray[1])))
                    .title(place.getName().toString())
            );
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            System.out.println("An error occurred: " + status);
        }
    });

}

private Location getLastKnownLocation() {
    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);;
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        if(Build.VERSION.SDK_INT >=23){
            if (Build.VERSION.SDK_INT >= 23) {
                if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                } else {
                    if (shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_FINE_LOCATION) || shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    }
                    requestPermissions(new String[]{
                            android.Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                    }, REQUEST_SEND_SMS);
                }
            }
        }
        Location l = mLocationManager.getLastKnownLocation(provider);
        System.out.println("last known location, provider: %s, location: %s");

        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            System.out.println("found best last known location: %s");
            bestLocation = l;
        }
    }
    if (bestLocation == null) {
        return null;
    }
    return bestLocation;
}
}

推荐答案

我认为我回答这个问题有点晚了.我在下面找到了最突出的解决方案.也许会帮助某人.直接解决方案是PlaceAutocompleteFragment API的setText方法.有关详细答案,请通过以下答案进行解答.

I think I'm li'l bit late to answer this question. I found the most prominent solution below. maybe it will help someone. Direct solution is setText method of PlaceAutocompleteFragment API. For Detailed answer please go through below answer.

  1. 加载Google地图
  2. 初始化PlaceAutocompleteFragment
  3. onMapReady方法中的getCurrentLocation
  4. 设置当前位置标记
  5. 现在,只需调用setAuto方法来设置PlaceAutocompleteFragment的名称. (例如sourcePlace.setText("Current Location");)
  1. Load the Google Map
  2. Init the PlaceAutocompleteFragment
  3. getCurrentLocation inside onMapReady Method
  4. set current location Marker
  5. Now, Simply set the name of PlaceAutocompleteFragment by calling its setText Method. (e.g. sourcePlace.setText("Current Location");)

注意:这是我发现的最简单的方法.尝试一下,如果它也适合您的要求.

Note: This is the simplest method I have found for my requirements. Try it, if it suits your requirement also.

这篇关于设置当前位置到位自动完成片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆