Android 如何通过发送start的latlong和autocomplete并在json响应中返回latlong来绘制从源到目标的路径 我能够从json sourcelatlong、json destinationlatlong绘制多段线,但无法在用户从其中一条多段线
如何通过发送start的latlong和autocomplete并在json响应中返回latlong来绘制从源到目标的路径Android 如何通过发送start的latlong和autocomplete并在json响应中返回latlong来绘制从源到目标的路径 我能够从json sourcelatlong、json destinationlatlong绘制多段线,但无法在用户从其中一条多段线,android,Android,如何通过发送start的latlong和autocomplete并在json响应中返回latlong来绘制从源到目标的路径 我能够从json sourcelatlong、json destinationlatlong绘制多段线,但无法在用户从其中一条多段线路线移动时绘制路线 我正在向服务器发送start latlong和end latlong,但用户移动时latlong会发生变化吗?或者不会更改,因为我已经从自动完成中选择了开始和结束 下面是我试图画路线的代码 公共类Fragment1扩展了片段
公共类Fragment1扩展了片段实现RoutingListener、GoogleAppClient.OnConnectionFailedListener、GoogleAppClient.ConnectionCallbacks{
私有静态最终int权限\请求\代码=1;
受保护的谷歌地图;
保护闭锁启动;
保护板条端;
//@InjectView(R.id.start)
自动完成文本视图启动;
//@InjectView(R.id.destination)
自动完成文本视图目的地;
//@InjectView(R.id.send)
图像视图发送;
私有静态最终字符串日志\u TAG=“MyActivity”;
受保护的GoogleapClient MGoogleapClient;
私人配售自动完成适应;
私有进程对话;
私有列表多段线;
沟通者;
地点经理地点经理;
视图;
LatLng源LatLng;
LatLng Destination Atlong;
字符串id;
GPSTracker-GPSTracker;
private static final int[]COLORS=新int[]{R.color.primary_dark,R.color.primary,R.color.primary_light,R.color.accent,R.color.primary_dark_material_light};
私有静态最终LatLngBounds BOUNDS_牙买加=新LatLngBounds(新LatLng(-57.965341647205726,144.9987719580531),
新车床(72.77492067739843,-9.998857788741589);
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
如果(视图==null){
视图=充气机。充气(R.layout.fragment\u内容物,容器,假);
通信器=新通信器();
gpsTracker=新的gpsTracker(getActivity());
}
//ButterKnife.inject(getActivity());
//getSupportActionBar().setDisplayShowHomeEnabled(true);l
starting=(AutoCompleteTextView)view.findviewbyd(R.id.start);
send=(ImageView)view.findViewById(R.id.send);
destination=(AutoCompleteTextView)view.findviewbyd(R.id.destination);
多段线=新的ArrayList();
mgoogleapclient=新的Googleapclient.Builder(getActivity())
.addApi(Places.GEO_数据_API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
初始化(getActivity());
mGoogleApiClient.connect();
SupportMapFragment mapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
if(mapFragment==null){
mapFragment=SupportMapFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.map,mapFragment.commit();
}
_map=mapFragment.getMap();
mAdapter=newplaceautocompletedatapter(getActivity(),android.R.layout.simple\u list\u item\u 1,
mGoogleApiClient,界限(牙买加,空);
/*
*根据适配器的位置更新自动完成适配器使用的边界
*地图。
* */
_map.setonCamerachenglistener(新的GoogleMap.onCamerachenglistener(){
@凌驾
摄影机更改上的公共空白(摄影机位置){
LatLngBounds bounds=_map.getProjection().getVisibleRegion().LatLngBounds;
mAdapter.后退边界(边界);
}
});
_map.getUiSettings().setZoomControlsEnabled(true);
_map.getUiSettings().setCompassEnabled(true);
_map.setPadding(10,10,0300);
_map.setPadding(10,10,0300);
CameraUpdate center=CameraUpdateFactory.newLatLng(newLatLng(gpsTracker.getLatitude(),gpsTracker.getLongitude());
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
MarkerOptions options=新的MarkerOptions();
options.position(新LatLng(gpsTracker.getLatitude(),gpsTracker.getLongitude());
图标(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
_map.addMarker(选项);
_地图。移动摄像机(中心);
_map.animateCamera(缩放);
如果(Build.VERSION.SDK_INT>=23){
if(getActivity().checkSelfPermission(Manifest.permission.ACCESS\u\u LOCATION)!=PackageManager.permission\u已授予){
if(shouldShowRequestPermissionRegulation(Manifest.permission.ACCESS\u\u位置)){
Toast.makeText(getActivity(),“需要权限”,Toast.LENGTH_SHORT.show();
}
requestPermissions(新字符串[]{Manifest.permission.ACCESS\u\u LOCATION},1);
}否则{
位置();
}
}否则{
位置();
}
/*
*将自动完成适配器添加到两个自动完成适配器
*文本视图。
* */
试一试{
启动.setAdapter(mAdapter);
destination.setAdapter(mAdapter);
}捕获(例外e){
Log.i(“adpter中的异常”,“e”);
}
/*
*根据选定的值设置起点和终点
*从自动完成文本视图。
* */
正在启动.setOnItemClickListener(
新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
最终位置AutoCompleteAdapter.PlaceAutocomplete项=mAdapter.getItem(位置);
最终字符串placeId=String.valueOf(item.placeId);
public class Fragment1 extends Fragment implements RoutingListener, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private static final int PERMISSION_REQUEST_CODE = 1;
protected GoogleMap _map;
protected LatLng start;
protected LatLng end;
// @InjectView(R.id.start)
AutoCompleteTextView starting;
// @InjectView(R.id.destination)
AutoCompleteTextView destination;
// @InjectView(R.id.send)
ImageView send;
private static final String LOG_TAG = "MyActivity";
protected GoogleApiClient mGoogleApiClient;
private PlaceAutoCompleteAdapter mAdapter;
private ProgressDialog progressDialog;
private List<Polyline> polylines;
Communicator communicator;
LocationManager locationManager;
View view;
LatLng sourcelatLng;
LatLng destinationlatlong;
String id;
GPSTracker gpsTracker;
private static final int[] COLORS = new int[]{R.color.primary_dark, R.color.primary, R.color.primary_light, R.color.accent, R.color.primary_dark_material_light};
private static final LatLngBounds BOUNDS_JAMAICA = new LatLngBounds(new LatLng(-57.965341647205726, 144.9987719580531),
new LatLng(72.77492067739843, -9.998857788741589));
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_content, container, false);
communicator = new Communicator();
gpsTracker = new GPSTracker(getActivity());
}
// ButterKnife.inject(getActivity());
// getSupportActionBar().setDisplayShowHomeEnabled(true);l
starting = (AutoCompleteTextView) view.findViewById(R.id.start);
send = (ImageView) view.findViewById(R.id.send);
destination = (AutoCompleteTextView) view.findViewById(R.id.destination);
polylines = new ArrayList<>();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
MapsInitializer.initialize(getActivity());
mGoogleApiClient.connect();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
}
_map = mapFragment.getMap();
mAdapter = new PlaceAutoCompleteAdapter(getActivity(), android.R.layout.simple_list_item_1,
mGoogleApiClient, BOUNDS_JAMAICA, null);
/*
* Updates the bounds being used by the auto complete adapter based on the position of the
* map.
* */
_map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
LatLngBounds bounds = _map.getProjection().getVisibleRegion().latLngBounds;
mAdapter.setBounds(bounds);
}
});
_map.getUiSettings().setZoomControlsEnabled(true);
_map.getUiSettings().setCompassEnabled(true);
_map.setPadding(10, 10, 0, 300);
_map.setPadding(10, 10, 0, 300);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude()));
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
_map.addMarker(options);
_map.moveCamera(center);
_map.animateCamera(zoom);
if (Build.VERSION.SDK_INT >= 23) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(getActivity(), " Permission is needed", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
location();
}
} else {
location();
}
/*
* Adds auto complete adapter to both auto complete
* text views.
* */
try {
starting.setAdapter(mAdapter);
destination.setAdapter(mAdapter);
} catch (Exception e) {
Log.i("Exception in adpter", "" + e);
}
/*
* Sets the start and destination points based on the values selected
* from the autocomplete text views.
* */
starting.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlaceAutoCompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(LOG_TAG, "Autocomplete item selected: " + item.description);
/*
Issue a request to the Places Geo Data API to retrieve a Place object with additional
details about the place.
*/
final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
// Request did not complete successfully
Log.e(LOG_TAG, "Place query did not complete. Error: " + places.getStatus().toString());
places.release();
return;
}
// Get the Place object from the buffer.
final Place place = places.get(0);
start = place.getLatLng();
}
});
}
});
destination.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlaceAutoCompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(LOG_TAG, "Autocomplete item selected: " + item.description);
/*
Issue a request to the Places Geo Data API to retrieve a Place object with additional
details about the place.
*/
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
// Request did not complete successfully
Log.e(LOG_TAG, "Place query did not complete. Error: " + places.getStatus().toString());
places.release();
return;
}
// Get the Place object from the buffer.
final Place place = places.get(0);
end = place.getLatLng();
}
});
}
});
/*
These text watchers set the start and end points to null because once there's
* a change after a value has been selected from the dropdown
* then the value has to reselected from dropdown to get
* the correct location.
* */
starting.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int startNum, int before, int count) {
if (start != null) {
start = null;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
destination.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (end != null) {
end = null;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequest();
}
});
return view;
}
public void sendRequest() {
if (Util.Operations.isOnline(getActivity())) {
route();
} else {
Toast.makeText(getActivity(), "No internet connectivity", Toast.LENGTH_SHORT).show();
}
}
public void route() {
if (start == null || end == null) {
if (start == null) {
if (starting.getText().length() > 0) {
starting.setError("Choose location from dropdown.");
} else {
Toast.makeText(getActivity(), "Please choose a starting point.", Toast.LENGTH_SHORT).show();
}
}
if (end == null) {
if (destination.getText().length() > 0) {
destination.setError("Choose location from dropdown.");
} else {
Toast.makeText(getActivity(), "Please choose a destination.", Toast.LENGTH_SHORT).show();
}
}
} else {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Fetching route information.", true);
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(start, end)
.build();
routing.execute();
}
}
@Override
public void onRoutingFailure(RouteException e) {
progressDialog.dismiss();
if (e != null) {
Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Something went wrong, Try again", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRoutingStart() {
}
@Override
public void onRoutingSuccess(List<Route> route, int shortestRouteIndex) {
progressDialog.dismiss();
CameraUpdate center = CameraUpdateFactory.newLatLng(start);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
_map.animateCamera(zoom);
_map.moveCamera(center);
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
}
polylines = new ArrayList<>();
//add route(s) to the map.
for (int i = 0; i < route.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(route.get(i).getPoints());
Polyline polyline = _map.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getActivity(), "Route " + (i + 1) + ": distance - " + route.get(i).getDistanceValue() + ": duration - " + route.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
// Start marker
// MarkerOptions options = new MarkerOptions();
// options.position(start);
// options.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
// _map.addMarker(options);
//
// // End marker
// options = new MarkerOptions();
// options.position(end);
// options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
// _map.addMarker(options);
//change for marker points
//String[] startlatlong =
String startone = start.toString();
// String[] startlatlong =startone.split(",");
// final double sourcelatitude = Double.parseDouble(startlatlong[0]);
// double sourcelongitude = Double.parseDouble(startlatlong[1]);
// String[] destlatlong = end.toString().split(",");
// double destlatitude = Double.parseDouble(destlatlong[0]);
// double destlongitude = Double.parseDouble(destlatlong[1]);
SessionManager sessionManager = new SessionManager(getActivity());
// System.out.println("==Sourcelatitude==="+sourcelatitude);
// System.out.println("===destlatitude==="+destlatitude);
id = sessionManager.getUserInfo();
System.out.println("==Sourcelatitude===" + start.toString());
System.out.println("===destlatitude===" + end.toString());
communicator.getPlaces(id, start.toString(), end.toString(), new Communicator.OnResultSuccess() {
@Override
public void onSuccess(Object object) {
LocationData mServerResponse = (LocationData) object;
if (mServerResponse != null) {
if (mServerResponse.getStatus() != null && mServerResponse.getStatus().equals("true")) {
List<UserLocation> locationList = mServerResponse.getData();
String id = locationList.get(0).getId();
if (locationList == null) {
double sourcelatitude = Double.parseDouble(locationList.get(1).getSrclatitude());
double sourcelongitude = Double.parseDouble(locationList.get(2).getSrclongitude());
sourcelatLng = new LatLng(sourcelatitude, sourcelongitude);
double destlatitude = Double.parseDouble(locationList.get(3).getDestlatitude());
double destlongitude = Double.parseDouble(locationList.get(4).getDestlongitude());
destinationlatlong = new LatLng(destlatitude, destlongitude);
MarkerOptions options = new MarkerOptions();
options.position(sourcelatLng);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
_map.addMarker(options);
options = new MarkerOptions();
options.position(destinationlatlong);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
_map.addMarker(options);
}
}
} else if (mServerResponse.getStatus() != null && mServerResponse.getStatus().equals("false")) {
Toast.makeText(getActivity(), "unable to get location", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "error in getting response", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailur(String fail) {
}
});
}
@Override
public void onRoutingCancelled() {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.v(LOG_TAG, connectionResult.toString());
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
location();
} else {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void location() {
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return TODO;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
_map.moveCamera(center);
_map.animateCamera(zoom);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
_map.moveCamera(center);
_map.animateCamera(zoom);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
}
}