Android 设置当前就地自动完成片段
我想在创建活动时将当前位置设置为位置自动完成片段 我能够加载GoogleMapsAPI,并且在我的应用程序中成功地实现了PlaceAutoComplete片段。但是,我希望place autocomplete fragment将当前位置设置为默认字符串in-place autocomplete fragment。就像优步一样。当我们打开Uber并点击编辑文本“去哪里?”时,它会要求我们输入或搜索目的地位置,并自动将位置设置为当前位置。我的代码如下:Android 设置当前就地自动完成片段,android,autocomplete,Android,Autocomplete,我想在创建活动时将当前位置设置为位置自动完成片段 我能够加载GoogleMapsAPI,并且在我的应用程序中成功地实现了PlaceAutoComplete片段。但是,我希望place autocomplete fragment将当前位置设置为默认字符串in-place autocomplete fragment。就像优步一样。当我们打开Uber并点击编辑文本“去哪里?”时,它会要求我们输入或搜索目的地位置,并自动将位置设置为当前位置。我的代码如下: import android.Manifest
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;
}
}
导入android.Manifest;
导入android.content.Context;
导入android.content.pm.PackageManager;
导入android.content.res.Resources;
导入android.location.Criteria;
导入android.location.location;
导入android.location.LocationManager;
导入android.os.Build;
导入android.support.v4.app.FragmentActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.Toast;
导入com.google.android.gms.common.api.Status;
导入com.google.android.gms.location.places.Place;
导入com.google.android.gms.location.places.PlaceDetectionApi;
导入com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
导入com.google.android.gms.location.places.ui.PlaceSelectionListener;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.OnMapReadyCallback;
导入com.google.android.gms.maps.SupportMapFragment;
导入com.google.android.gms.maps.model.CameraPosition;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.MapStyleOptions;
导入com.google.android.gms.maps.model.MarkerOptions;
导入java.util.array;
导入java.util.List;
公共类MapsActivity扩展了FragmentActivity在MapReadyCallback上的实现{
私有谷歌地图;
私有静态最终整数请求\u发送\u短信=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
试一试{
//使用定义的JSON对象自定义底图的样式
//在原始资源文件中。
布尔成功=mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
这是R.raw.茄子(风格);
如果(!成功){
Log.e(“MapsActivityRaw”,“样式解析失败”);
}
}catch(Resources.notfounde异常){
Log.e(“MapsActivityRaw”,“找不到样式”,e);
}
//在Sydney添加一个标记并移动相机
/*悉尼LatLng=新LatLng(-34151);
mMap.addMarker(新MarkerOptions().position(sydney.title)(“悉尼的标记”);
mMap.moveCamera(CameraUpdateFactory.newLatLng(悉尼))*/
LocationManager LocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
标准=新标准();
如果(Build.VERSION.SDK_INT>=23){
如果(Build.VERSION.SDK_INT>=23){
if(checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.permission_已授予| | checkSelfPermission(android.Manifest.permission.ACCESS_粗略_LOCATION)==PackageManager.permission_已授予){
}否则{
if(shouldShowRequestPermissionRegulation(android.Manifest.permission.ACCESS_FINE_LOCATION)| | shouldShowRequestPermissionRegulation(android.Manifest.permission.ACCESS_粗略_LOCATION)){
}
requestPermissions(新字符串[]){
android.Manifest.permission.ACCESS\u FINE\u位置,
android.Manifest.permission.ACCESS\u位置
},请求发送短信);
}
}
}
位置=getLastKnownLocation();
如果(位置!=null)
{
this.mMap.getUiSettings().setMyLocationButtonEnabled(false);
this.mMap.setMyLocationEnabled(true);
GPSTracker tracker=新的GPSTracker(本);
双纬度=0;
双经度=0;
如果(!tracker.canGetLocation()){
tracker.showSettingsAlert();
}否则{
纬度=tracker.getLatitude();
longitude=tracker.getLongitude();
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(新LatLng(纬度、经度),15));
}否则{
Toast.makeText(getApplicationContext(),“位置为空”,Toast.LENGTH_LONG.show();
}
PlaceAutocompleteFragment autocompleteFragment=(PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place\u autocomplete\u fragment);
autocompleteFragment.setText(“”);
autocompleteFragment.setOnPlaceSelectedListener(新的PlaceSelectionListener(){
@凌驾
已选定地点上的公共作废(地点){
//TODO:获取有关所选地点的信息。
System.out.println(“地名:+Place.getName());
System.out.println(“位置ID:+Place.getId());
System.out.println(“地点地址:+Place.getAddress());
System.out.println(“Place-LatLng:+Place.getLatLng());
字符串latLng=place.getLatLng().toString();
latLng=latLng。替换(“lat/lng:(“,”);
latLng=latLng。替换(“)”,“);
字符串[]latLngArray=latLng.split(“,”);
System.out.println(“仅纬度:+latLngArray[0]);
System.out.println(“仅经度:+latlngaray[1]);
mMap.clear();
mMap.addMarker(新标记选项()
.职位(
<android.support.v7.widget.CardView
android:layout_marginTop="60dp"
android:layout_height="50dp"
android:layout_width="match_parent"
android:id="@+id/cardView">
<fragment android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/place_autocomplete_fragment"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
private void autocom()
{
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
LatLng string_location = place.getLatLng();
String address = (String) place.getAddress();
String name = (String) place.getName();
// Log.i("LocationLatlang", String.valueOf(string_location));
//Log.i("LocationAddress", address);
//Log.i("Locationname", name);
//Log.i("pppp", "Place: " + place.getName());
}
@Override
public void onError(Status status) {
Log.i("ppperror", "An error occurred: " + status);
}
});
}