Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 谷歌地图标记标题android_Java_Android_Android Fragments_Android Maps - Fatal编程技术网

Java 谷歌地图标记标题android

Java 谷歌地图标记标题android,java,android,android-fragments,android-maps,Java,Android,Android Fragments,Android Maps,我正试图向大家展示离我目前所在地最近的大使馆。我可以打印我目前所在地的所有大使馆,但我面临的问题是,所有大使馆的名称都是相同的。因为所有的大使馆都展示了和这张照片一样的标题 我只想在标题中显示每个大使馆的名称。目前只展示“马耳他大使馆”。下面是我的代码,请告诉我哪里错了。我是Android新手,这是我的第一个项目,如果我的问题不够强烈,请提前道歉。下面还要提前感谢我的代码`公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现, Goog

我正试图向大家展示离我目前所在地最近的大使馆。我可以打印我目前所在地的所有大使馆,但我面临的问题是,所有大使馆的名称都是相同的。因为所有的大使馆都展示了和这张照片一样的标题

我只想在标题中显示每个大使馆的名称。目前只展示“马耳他大使馆”。下面是我的代码,请告诉我哪里错了。我是Android新手,这是我的第一个项目,如果我的问题不够强烈,请提前道歉。下面还要提前感谢我的代码`公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现, GoogleAppClient.ConnectionCallbacks, GoogleAppClient.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 (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);

        }

    }

}
GoogleMap-mMap;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
位置请求mLocationRequest;
私有布尔标志=true;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager();
getMapAsync(这个);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
mMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
//初始化Google Play服务
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
}否则{
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
未连接的公共空间(捆绑包){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(1000);
mlLocationRequest.setFastTestInterval(1000);
mLocationRequest.setPriority(位置请求、优先级、平衡、功率、精度);
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
已更改位置上的公共无效(位置){
mLastLocation=位置;
if(mCurrLocationMarker!=null){
mCurrLocationMarker.remove();
}
//放置当前位置标记
LatLng LatLng=新LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions MarkerOptions=新MarkerOptions();
标记选项位置(板条);
标记选项。标题(“当前位置”);
图标(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker=mMap.addMarker(markerOptions);
//移动地图照相机
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
//停止位置更新
if(mGoogleApiClient!=null){
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
}
新建getEmbassyPoint().execute(新建LatLng(location.getLatitude(),location.getLongitude());
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
}
公共静态final int MY_PERMISSIONS_REQUEST_LOCATION=99;
公共布尔值checkLocationPermission(){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
!=PackageManager.权限(已授予){
//询问用户是否需要解释
如果(活动公司)应显示请求许可理由(此,
清单.权限.访问(位置){
//向用户显示解释*异步*--不阻止
//此线程正在等待用户的响应!在用户
//请查看说明,然后重试请求权限。
//显示说明后提示用户
ActivityCompat.requestPermissions(此,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
我的\权限\请求\位置);
}否则{
//不需要解释,我们可以申请许可。
ActivityCompat.requestPermissions(此,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
我的\权限\请求\位置);
}
返回false;
}否则{
返回true;
}
}
@凌驾
public void onRequestPermissionsResult(int-requestCode,字符串权限[],int[]grantResults){
开关(请求代码){
案例我的权限请求位置:{
//如果取消请求,则结果数组为空。
如果(grantResults.length>0
&&grantResults[0]==PackageManager.PERMISSION\u已授予){
//已授予权限。请执行以下操作:
//联系您需要执行的相关任务。
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
如果
name = element.getAsJsonObject().get("name").getAsString();
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;
}
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)));

    }
}