2016-12-02 102 views
1

我想显示离我目前所在位置最近的所有使馆。我可以从当前位置打印所有大使馆,但我面临的问题是所有大使馆的标题都一样。因为所有使馆在这张照片中都显示出相同的标题。 enter image description hereGoogle地图标记标题android

我想要做的就是在标题中显示每个大使馆的名称。目前只展示“马耳他大使馆”。以下是我的代码请建议我在哪里我错了。我是Android新手,这是我的第一个项目,所以如果我的问题不够强,请提前道歉。也低于提前很多感谢是我的code`public类MapsActivity扩展AppCompatActivity实现OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener的{

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 (android.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 (android.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

在onPostExecute您使用的是ArrayListLatLng

将其更改为自定义对象的ArrayList

在自定义对象中,您需要LatLngMarker的标题。

你的错误就出在这里:

name = element.getAsJsonObject().get("name").getAsString(); 

你重置每一次你解析的JSONObject在循环字符串名称。您需要在您的对象进行存储这个

像这样的东西应该工作:这不会编译,但变化是很容易的,改变一切从经纬度的ArrayList中,以CustomObject

class getEmbassyPoint extends AsyncTask<LatLng, String, ArrayList<CustomObject>> { 

    double x, y; 
    String name; 

    private LatLng myPoint; 


    @Override 
    protected ArrayList<CustomObject> 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"; 



     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<CustomObject> 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()); 

       CustomObject customObject = new CustomObject; 
       customObject.title = element.getAsJsonObject().get("name").getAsString(); 
       customObject.latLng = new LatLng(x,y); 
       listt.add(customObject); 

      } 

      return (ArrayList<CustomObject>) listt; 

     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    @Override 
    protected void onPostExecute(ArrayList<CustomObject> latLngs) { 
     super.onPostExecute(latLngs); 

     List<Marker> markers = new ArrayList<Marker>(); 

     for (CustomObject latLng : latLngs){ 

      Marker marker = mMap.addMarker(new MarkerOptions().position(latLng.latLng).title(latLng.title).icon(BitmapDescriptorFactory.fromResource(R.drawable.mosque))); 
      markers.add(marker); 
      MarkerOptions mp = new MarkerOptions(); 
      mp.title(latLng.title); 

     } 

    } 

} 

的ArrayList您的自定义对象:

private class CustomObject { 
    public LatLng latLng; 
    public String title; 
} 
+0

请问您可以在一些代码中写下这些信息对我来说是不够的,会明白这一点。谢谢 –

+0

代码为你写。 – apmartin1991

+0

只需再次更新,代码也将编译。 – apmartin1991

0

ArrayList<LatLng> doInBackground(LatLng... params)方法,你不应该return (ArrayList<LatLng>) listt;。相反,您应该返回一个可迭代对象,该对象具有属性LatLng以保存纬度/经度信息以及String属性以保存标记名称。然后在您的protected void onPostExecute()方法中,您可以传递该可迭代对象并使用forloop以名称设置标记的title属性。

class LocationInfo 
{ 
    public LocatioInfo(LatLng latlng, string name) 
    { 
     this.latlng = latlng; 
     this.name = name; 
    } 
    LatLng latlng; 
    String name; 
} 

ArrayList<LocationInfo> doInBackground(LocationInfo... params) 
{ 
    ... 
    List<LocationInfo> listt = new ArrayList<LocationInfo>(); 
    for (JsonElement element : jsonArray) 
    { 
     ... 
     LatLng latlng = new LatLng(x, y); 
     listt.add(new LocationInfo(latlng, name)); 
    } 
} 

protected void onPostExecute(ArrayList<LocationInfo> locationInfos) 
{ 
    for (locationInfo locationInfo : locationInfos) 
    { 
     ... 
     LatLng l = locationInfo.latlng; 
     String n = locationInfo.name; 
     Marker marker = mMap.addMarker(new MarkerOptions().position(l).title(n).icon(BitmapDescriptorFactory.fromResource(R.drawable.mosque))); 

    } 
}