谷歌地图标记标题android

时间:2016-12-02 14:46:25

标签: java android android-fragments android-maps

我试图从我当前的位置显示所有最近的大使馆。我可以从我当前的位置打印所有大使馆,但我面临的问题是所有大使馆的标题是相同的。所有大使馆都在这张照片中显示相同的标题。enter image description here

我想做的就是在标题中显示每个大使馆的名称。目前只展示“马耳他大使馆”。以下是我的代码请告诉我我错在哪里。我是Android新手,这是我的第一个项目,如果我的问题不够强,请提前道歉。还有很多感谢以下是我的代码`公共类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 个答案:

答案 0 :(得分:1)

在onPostExecute中

您正在使用ArrayList LatLng

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

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

你的错误在于:

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

每次解析循环中的JSONObject时,都会重置String名称。您需要将其存储在对象中

这样的东西应该可以工作:这不会编译,但是更改非常简单,将所有内容从LatLng的ArrayList更改为CustomObject的arrayList

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

        }

    }

}

您的自定义对象:

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