private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_ciudad_sales);
// 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);
}
/**
* 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;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-19.047696, -65.260062),15));
// Add a marker in Sydney and move the camera
LatLng sucre = new LatLng(-19.047696, -65.260062);
mMap.addMarker(new MarkerOptions().position(sucre).title("Berlin"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sucre));
}
}
我尝试了很多东西,但到目前为止没有任何作用,所以我把它作为一个例子,但我真的想要打开mapsactivity和相机变焦并转到你的实际位置而不点击任何东西或制作标记...... / p>
答案 0 :(得分:0)
我在我的应用中使用此代码首先在地图中显示当前位置。之后,您可以拖动指针imageMarker
,然后您将获得地图中反映的更改位置。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">
<LinearLayout
android:id="@+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical">
<TextView android:gravity="center_vertical"
android:id="@+id/Locality"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_btn_current_location"
android:drawableStart="@drawable/ic_btn_current_location"
android:drawablePadding="20dp"
android:ellipsize="end"
android:padding="10dp"
android:maxLines="1"
android:text="@string/click_to_change_loc" />
</LinearLayout>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/container_toolbar">
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/locationMarker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/locationMarkertext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rounded_corner_map"
android:gravity="center"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text="@string/fetch_loc"
android:textColor="@android:color/white" />
<ImageView
android:id="@+id/imageMarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add_marker" />
</LinearLayout>
</FrameLayout>
</RelativeLayout>
&#13;
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();
}
}
}
&#13;
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();
}
}
&#13;
答案 1 :(得分:0)
Google地图不提供访问当前位置的公开方法。 要放大当前位置,首先需要获取当前位置。最好的方法是使用Google位置服务。
布局文件(没有什么特别的只是带有地图片段的布局):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="abhishek.shopbill.activities.MapsActivity">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
活动代码(我已嵌套所有回调以更好地理解流程):
public class MapsActivity extends AppCompatActivity {
GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Step1: find the map fragment.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
//Step 2: configure the GoogleApiClient. This is used for location services.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
//Step 3: After the GoogleApiClient is connected get the Map.
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
try {
googleMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
//no permissions granted
e.printStackTrace();
}
//Step 4: Get the current location(Check the getLastLocation
//method at the bottom)
Location selectedLocation = getLastLocation();
//Step 5(Last): Animate the map to the postion
if (selectedLocation != null) {
//Zoom in and animate the camera.
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(selectedLocation.getLatitude(), selectedLocation.getLongitude()))
.zoom(17).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//only zoom in don't animate
/*googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(selectedLocation.getLatitude(), selectedLocation.getLongitude())));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));*/
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
//Connection suspended code here.
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
//connection failed code here
}
})
.addApi(LocationServices.API)
.build();
}
//Don't forget to connect the GoogleApiClient
mGoogleApiClient.connect();
}
public Location getLastLocation() {
//Check for permission first
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}
//using the FusedLocationApi get the last location
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
return lastLocation;
}
@Override
protected void onDestroy() {
//Don't forget to disconnect
mGoogleApiClient.disconnect();
super.onDestroy();
}
}
祝你有愉快的一天..
答案 2 :(得分:0)
您的问题不明确,但这行代码
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-19.047696, -65.260062),15));