java谷歌地图标记标题安卓
我正试图向大家展示离我目前所在地最近的大使馆。我可以打印我目前所在地的所有大使馆,但我面临的问题是,所有大使馆的名称都是相同的。因为所有的大使馆都展示了和这张照片一样的标题
我只想在标题中显示每个大使馆的名称。目前只展示“马耳他大使馆”。下面是我的代码,请告诉我哪里错了。我是Android新手,这是我的第一个项目,如果我的问题不够强烈,请提前道歉。下面还要提前感谢我的代码`公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现, GoogleapClient。连接回调, GoogleapClient。OnConnectionFailedListener, 位置侦听器{
GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (安卓.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (安卓.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
new getEmbassyPoint().execute(new LatLng(location.getLatitude(), location.getLongitude()));
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
class getEmbassyPoint extends AsyncTask<LatLng, String, ArrayList<LatLng>> {
double x, y;
String name;
private LatLng myPoint;
@Override
protected ArrayList<LatLng> doInBackground(LatLng... params) {
myPoint = params[0];
String s = "https://maps.googleapis.com/maps/api/place/nearbysearch" + "/json?location=" + myPoint.latitude + "," + myPoint.longitude
+ "&radius=50000&types=embassy&name=ireland" + "&key=my api key";
Log.i("app", s);
try {
URL url = new URL(s);
BufferedReader r = new BufferedReader(new InputStreamReader(((HttpURLConnection) url.openConnection()).getInputStream()));
JsonParser jp = new JsonParser();
JsonElement jsonElement = jp.parse(r);
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("results");
List<LatLng> listt = new ArrayList<>();
for (JsonElement element : jsonArray) {
name = element.getAsJsonObject().get("name").getAsString();
x = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lat").getAsString());
y = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lng").getAsString());
listt.add(new LatLng(x,y));
}
return (ArrayList<LatLng>) listt;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(ArrayList<LatLng> latLngs) {
super.onPostExecute(latLngs);
for (LatLng latLng : latLngs){
Log.i("app", "onPostExecute: lat: " + latLng.latitude);
List<Marker> markers = new ArrayList<Marker>();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).title(name).icon(BitmapDescriptorFactory.fromResource(R.drawable.mosque)));
markers.add(marker);
MarkerOptions mp = new MarkerOptions();
mp.title(name);
}
}
}
}`
# 1 楼答案
在
ArrayList<LatLng> doInBackground(LatLng... params)
方法中,不应该return (ArrayList<LatLng>) listt;
。相反,您应该返回一个iterable对象,该对象具有属性LatLng
来保存纬度/经度信息,以及属性String
来保存标记名。然后,在protected void onPostExecute()
方法中,可以传递iterable对象,并使用forloop将标记的title属性设置为name# 2 楼答案
在onPostExecute中,您使用的是
ArrayList
的LatLng
将其更改为自定义对象的
ArrayList
在自定义对象中,需要
LatLng
和Marker
的标题你的错误就在这里:
每次解析循环中的JSONObject时都会重置字符串名。您需要将其存储在对象中
类似的东西应该可以工作:这不会编译,但更改非常简单,从LatLng的ArrayList更改为CustomObject的ArrayList
您的自定义对象: