我有一个地图应用程序,显示德黑兰的自行车停留。 看起来像这样
我想要做的是每当我点击其中一个微调项目时,它会紧密缩放该项目的位置。像这样:
我试图做对,但它不起作用。
这是我的代码:
public class MainActivity extends android.support.v4.app.FragmentActivity implements android.widget.AdapterView.OnItemClickListener, LocationListener {
public Marker marker1;
GoogleMap googleMap;
GoogleMap mGoogleMap;
Spinner spr_place_list;
Toolbar toolbar;
ImageView menu_icon;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
ImageView share_button;
double mLatitude = 0;
double mLongitude = 0;
static final LatLng JAVANMARDAN = new LatLng(35.747394, 51.267577);
static final LatLng BAKERYHIPERSTAR = new LatLng(35.725623, 51.295175);
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_two);
toolbar = (Toolbar) findViewById(R.id.toolbar);
menu_icon = (ImageView) findViewById(R.id.menu_icon);
//SHARE BUTTON
View.OnClickListener handler = new View.OnClickListener() {
@Override
public void onClick(View v) {
shareUrl();
}
};
findViewById(R.id.share_button).setOnClickListener(handler);
// A rray of place types
mPlaceType = getResources().getStringArray(R.array.place_name);
// Array of place type names
// mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceType);
// Getting reference to the Spinner
spr_place_list = (Spinner) findViewById(R.id.spr_place_list);
final List<String> categories = new ArrayList<String>();
categories.add("جوانمردان 1");
categories.add("هایپر استار");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
// Setting adapter on Spinner to set place types
spr_place_list.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map);
fragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
Marker marker1 = googleMap.addMarker(new MarkerOptions().title("بوستان جوانمردان").position(JAVANMARDAN));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(JAVANMARDAN, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
googleMap.addMarker(new MarkerOptions().title("بزرگراه شهید باکری - هایپر استار").position(BAKERYHIPERSTAR));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
});
spr_place_list.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String selectedItem = parent.getItemAtPosition(position).toString();
if (selectedItem.equals("جوانمردان 1")) {
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Enabling MyLocation in Google Map
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
private void shareUrl() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//TEXT
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "اپلیکیشن دوچرخه سواری");
shareIntent.putExtra(Intent.EXTRA_TEXT, "؟؟؟؟؟");
//IMAGE
String imagePath = Environment.getExternalStorageState() +
"/share_image.png";
File imageFileShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileShare);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share link!"));
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Ex downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
if (selectedItem.equals("جوانمردان 1")) {
googleMap.addMarker(new MarkerOptions().title("بزرگراه شهید باکری - هایپر استار").position(BAKERYHIPERSTAR));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR, 21));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(21), 2000, null);
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR,20));
//googleMap.animateCamera(CameraUpdateFactory.zoomTo(21), 5000, null);
}
}
/**
* A class, to download Google Places
*/
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
@Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String, String>> list) {
// Clears all the existing markers
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
在eventListener中,尝试添加
map.setZoom(9);
map.panTo(curmarker.position);
如W3Schools Tutorial中所述 - Google Maps Events,将事件处理程序附加到标记处,该标记在单击时缩放地图,然后使用panTo()
将地图平移回标记。
您可以在W3schools教程中自己尝试,并在此SO帖子中给出解决方案 - Zoom in to marker google.maps也可能有所帮助。