public class FetchAddressIntentService extends IntentService {
private static final String TAG = "FetchAddressIS";
protected ResultReceiver mReceiver;
public FetchAddressIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
String errorMessage = "";
mReceiver = intent.getParcelableExtra(AppUtils.LocationConstants.RECEIVER);
if (mReceiver == null) {
Log.wtf(TAG, "No receiver received. There is nowhere to send the results.");
return;
}
Location location = intent.getParcelableExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA);
if (location == null) {
errorMessage = getString(R.string.no_location_data_provided);
Log.wtf(TAG, errorMessage);
deliverResultToReceiver(AppUtils.LocationConstants.FAILURE_RESULT, errorMessage, null);
return;
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
String result = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
} catch (IOException ioException) {
errorMessage = getString(R.string.service_not_available);
//Log.e(TAG, errorMessage, ioException);
try {
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
String latlngStr = String.valueOf(newLatLng.latitude)+","+String.valueOf(newLatLng.longitude);
String googleapiurl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlngStr + "&sensor=true";
Log.e("sammy_error_googleapi", googleapiurl);
Log.e("sammy_error_location", newLatLng.toString());
Log.e("sammy_error_latitude", String.valueOf(newLatLng.latitude));
Log.e("sammy_error_longitude", String.valueOf(newLatLng.longitude));
HttpGet httpGet = new HttpGet(googleapiurl);
HttpClient client = new DefaultHttpClient();
StringBuilder stringBuilder = new StringBuilder();
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
if (jsonObject.getString("status").equals("OK")) {
JSONArray array = jsonObject.getJSONArray("results");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(0);
result = obj.getString("formatted_address");
String regex = "null\\b\\s*";
result = result.replaceAll(regex,"");
System.out.println("myaddress " + result);
}
deliverResultToReceiver(AppUtils.LocationConstants.SUCCESS_RESULT, result, null);
}
} catch (ClientProtocolException cpe) {
Log.e("TAG", "ClientProtocolException", cpe);
} catch (IOException ioe) {
Log.e("TAG", "IOException", ioe);
}catch (JSONException jsone) {
Log.e("TAG", "JSONException", jsone);
}
} catch (IllegalArgumentException illegalArgumentException) {
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " +"Latitude = " + location.getLatitude() +", Longitude = " + location.getLongitude(), illegalArgumentException);
}
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(AppUtils.LocationConstants.FAILURE_RESULT, errorMessage, null);
} else {
Address address = addresses.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(" ");
}
sb.append(address.getLocality()).append(" ");
sb.append(address.getPostalCode()).append(" ");
sb.append(address.getCountryName());
result = sb.toString();
String regex = "null\\b\\s*";
result = result.replaceAll(regex,"");
Log.e("TAG", "GEOCODE_RESULT "+result);
deliverResultToReceiver(AppUtils.LocationConstants.SUCCESS_RESULT, result, address);
}
}
/**
* Sends a resultCode and message to the receiver.
*/
private void deliverResultToReceiver(int resultCode, String message, Address address) {
try {
Bundle bundle = new Bundle();
bundle.putString(AppUtils.LocationConstants.RESULT_DATA_KEY, message);
if(address!=null){
bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_AREA, address.getSubLocality());
bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_CITY, address.getLocality());
bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_STREET, address.getAddressLine(0));
}
mReceiver.send(resultCode, bundle);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MapLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private MapView mMapView;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final Integer LOC_PERM = 0x1;
private static String TAG = "MAP LOCATION";
private TextView mLocationMarkerText, mLocationText;
private LatLng mCenterLatLong;
private AddressResultReceiver mResultReceiver;
protected String mAddressOutput, mAreaOutput, mCityOutput, mStreetOutput;
private String addressStr, latStr, lngStr, userid;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.maplocation, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("MY LOCATION");
if (getActivity() != null) {
mMapView = (MapView) view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
}
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
mLocationMarkerText = (TextView) view.findViewById(R.id.locationMarkertext);
mLocationText = (TextView) view.findViewById(R.id.Locality);
mLocationText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openAutocompleteActivity();
}
});
mResultReceiver = new AddressResultReceiver(new Handler());
if (checkPlayServices()) {
if (!AppUtils.isLocationEnabled(getActivity())) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage("Location not enabled!");
dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
paramDialogInterface.dismiss();
}
});
dialog.show();
}
buildGoogleApiClient();
} else {
Toast.makeText(getActivity(), "Location not supported in this device", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "OnMapReady");
if (mMapView != null)
mMap = googleMap;
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
Log.d("Camera postion change" + "", cameraPosition + "");
mCenterLatLong = cameraPosition.target;
mMap.clear();
try {
Location mLocation = new Location("");
mLocation.setLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude);
latStr = String.valueOf(mCenterLatLong.latitude);
lngStr = String.valueOf(mCenterLatLong.longitude);
Log.e("sammy_onMapReady", "LAT: " + latStr + " LNG: " + lngStr);
startIntentService(mLocation);
//mLocationMarkerText.setText("Lat : " + mCenterLatLong.latitude + "," + "Long : " + mCenterLatLong.longitude);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void onConnected(Bundle bundle) {
System.out.println("sammy_onConnected");
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
System.out.println("sammy_onConnected_loc "+latStr+" "+lngStr);
changeMap(mLastLocation);
} else
try {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
try {
if (location != null)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onStart() {
super.onStart();
try {
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
}
return false;
}
return true;
}
private void changeMap(Location location) {
System.out.println("sammy_reached_changeMap");
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mMap != null) {
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng latLong;
double latitude = Double.parseDouble(lat_);
double longitude = Double.parseDouble(lang_);
latLong = new LatLng(latitude, longitude);
Location location1 = new Location("");
location1.setLatitude(latLong.latitude);
location1.setLongitude(latLong.longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
latStr = String.valueOf(location1.getLatitude());
lngStr = String.valueOf(location1.getLongitude());
Log.e("sammy_changeMap","LAT: "+latStr+" LNG: "+lngStr);
startIntentService(location1);
} else {
Toast.makeText(getActivity(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
System.out.println("sammy_reached_onReceiveResult");
Log.e("sammy","reached_onReceiveResult");
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
mStreetOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
Log.e("sammy","address "+mAddressOutput+" area "+mAreaOutput+" city "+mCityOutput+" state "+mStreetOutput);
try {
addressStr = new LinkedHashSet<String> (Arrays.asList(mAddressOutput.split(" "))).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", " ");
mLocationMarkerText.setText(addressStr);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
protected void startIntentService(Location mLocation) {
Intent intent = new Intent(getActivity(), FetchAddressIntentService.class);
intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
getActivity().startService(intent);
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
你的问题有点不清楚。你的真实位置究竟是什么意思?你当前的位置还是纬度/经度坐标? –
你为什么用Javascript标记? –