Android Google Maps API v2在地图上放置标记

时间:2014-11-10 10:44:04

标签: java android google-maps

通过从数据库下载位置值,可以在其上放置标记的地图。但只有在激活onResume()后才能直观显示。这是一种放置标记的方法

public void place(){

      for (int i = 0; i<user_sex.length; i++){
            //someone = new MarkerOptions().position(new LatLng(xx[i], yy[i])).title("Вы здесь!");
            if (user_sex[i]==1){

            map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
            list.put(new LatLng(xx[i],yy[i]), i);

            }
            if (user_sex[i]==2){
                //m[i]=map.addMarker(new MarkerOptions().title("Посмотреть").position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
                map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
                list.put(new LatLng(xx[i],yy[i]), i);
            }else{
                if(xx[i]!=0 && yy[i]!=0 && (user_sex[i] < 1)){
                    //m[i]=map.addMarker(new MarkerOptions().title("Посмотреть").position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
                map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
                list.put(new LatLng(xx[i],yy[i]), i);
                }
                }
            //map.addMarker(someone);
        }
  }

但在这种情况下,我可以在不重新启动活动的情况下看到它们

CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(x, y)).zoom(16).build();
        map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


        place();
        this.onResume();

但是这个决定会导致管理卡出现问题 - 如果您移动相机,它会返回到该位置,并且当缩放时 - 返回缩放(16)。有解决方案吗?我的onResume()在下面

@Override
  protected void onResume(){
      super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            1000 * 10, 10, locationListener);
        locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
            locationListener);
        checkEnabled();
  }

以下全文MapActivity:

 package com.pavloid21.vk;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.LinearLayout;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.pavloid21.vk.R;
import com.pavloid21.vk.ProfileActivity;
import com.sbstrm.appirater.Appirater;
import com.startad.lib.SADView;

public class MapActivity extends FragmentActivity{

     SharedPreferences spref, mpref;
     Editor editor;
     Thread thrd;
     boolean flag;
     HttpResponse response = null;
     String token_user;
     int sex;
     long usr;
     long ID;
     static double x, y, lastX, lastY;
     static int count = 0;
     SupportMapFragment mapFragment;
     private LocationManager locationManager;
      GoogleMap map;
      Map<LatLng, Integer> list = new HashMap();
      final String TAG = "myLogs";
      private ProgressDialog pDialog;
      long[] vkIDs;
      int[] user_sex;
      double[] xx;
      double[] yy;
      String[] name;
      String[] m;
      MarkerOptions someone;
      String nm;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);

        vkIDs = new long[100];
        user_sex = new int[100];
        xx = new double[100];
        yy = new double[100];
        name = new String[100];



        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);

        mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
        map = mapFragment.getMap();
        if (map == null) {
          finish();
          return;
        }


      }

      @Override
      protected void onResume(){
          super.onResume();
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                1000 * 10, 10, locationListener);
            locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
                locationListener);
            checkEnabled();
      }

      @Override
      protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(locationListener);
      }

      private LocationListener locationListener = new LocationListener(){
          @Override
            public void onLocationChanged(Location location) {
              showLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
              checkEnabled();
            }

            @Override
            public void onProviderEnabled(String provider) {
              checkEnabled();
              showLocation(locationManager.getLastKnownLocation(provider));



            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
              if (provider.equals(LocationManager.GPS_PROVIDER)) {
                  Log.d("loction CHECK","Status: GPS "+ String.valueOf(status));

              } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
                  Log.d("loction CHECK","Status: NET "+ String.valueOf(status));
              }
            }
      };

      private void showLocation(Location location) {
            if (location == null)
              return;
            if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                Log.d("loction CHECK","Status: GPS "+ formatLocation(location));

            } else if (location.getProvider().equals(
                LocationManager.NETWORK_PROVIDER)) {
                Log.d("loction CHECK","Status: NET "+ formatLocation(location));
            }

            x = location.getLatitude();
            y = location.getLongitude();


            MarkerOptions marker = new MarkerOptions().position(new LatLng(x, y)).title("Вы здесь!");
            marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

            Appirater.appLaunched(this);
            map.setOnInfoWindowClickListener(new OnInfoWindowClickListener(){
                @Override
                public void onInfoWindowClick(Marker marker) {

                   if (list.containsKey(marker.getPosition())){
                   int i = list.get(marker.getPosition());

                   Intent intent = new Intent(MapActivity.this,ProfileActivity.class);
                   ProfileActivity.setID(vkIDs[i]);
                   startActivity(intent);

                   }
                }
            });
            if (count < 1) {

              map.addMarker(marker);

              mpref = getSharedPreferences("pref", Context.MODE_PRIVATE);
              flag = mpref.getBoolean("geo", true);

              if(flag == true){
              new Thread(new Runnable() {
                    @Override
                    public void  run(){

                              DefaultHttpClient hc = new DefaultHttpClient();  
                                ResponseHandler<String> res = new BasicResponseHandler();  
                                spref = getSharedPreferences("SETTING", Context.MODE_PRIVATE);

                                if (spref.contains("IDUSER")){
                                usr = spref.getLong("IDUSER", 0);
                                nm = spref.getString("NAME", "");
                                sex = spref.getInt("SEX", 0);
                                //token_user = spref.getString("TOKEN", "");
                                //sex = spref.getInt("SEX", 0);
                                //nm = spref.getString("NAME", "");
                                }
                                HttpGet http;
                                http = new HttpGet("http://hdwallpapers.orisale.ru//set_mylocation.php?vkid="+usr+"&name="+nm+"&sex="+sex+"&x="+ x +"&y="+ y);

                                Log.d("SEX!!!!!!!!!!!!!!!!", ""+sex);
                                try {
                                    String response = hc.execute(http, res);
                                } catch (ClientProtocolException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                }).start();
              } else {}
              Thread getPeopleThrd = new Thread(new Runnable(){
                    @Override
                    public void run(){
                        JSONParser jsonParser = new JSONParser();
                        JSONObject json = jsonParser.getJSONFromUrl("http://hdwallpapers.orisale.ru//get_around.php?&x="+ x +"&y="+ y);

                        JSONArray array = null;
                      try {
                        array = json.getJSONArray("locations");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < array.length(); i++){
                        try {
                            JSONObject around = array.getJSONObject(i);
                            vkIDs[i] = (around.getLong("vkid"));
                            user_sex[i] = (around.getInt("sex"));
                            xx[i] = (around.getDouble("x"));
                            yy[i] = (around.getDouble("y"));
                            name[i] = around.getString("name");
                            //name[i] = frnd_name(vkIDs[i]);
                            //Log.d("",name[i]);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                    }
                });
                getPeopleThrd.start(); 
            count += 1;

            };



            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(x, y)).zoom(16).build();
            map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            //frnd_name(usr);
            place();
            this.onResume();
          }

      public void place(){

          for (int i = 0; i<user_sex.length; i++){
                //someone = new MarkerOptions().position(new LatLng(xx[i], yy[i])).title("Вы здесь!");
                if (user_sex[i]==1){

                map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
                list.put(new LatLng(xx[i],yy[i]), i);

                }
                if (user_sex[i]==2){
                    //m[i]=map.addMarker(new MarkerOptions().title("Посмотреть").position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
                    map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
                    list.put(new LatLng(xx[i],yy[i]), i);
                }else{
                    if(xx[i]!=0 && yy[i]!=0 && (user_sex[i] < 1)){
                        //m[i]=map.addMarker(new MarkerOptions().title("Посмотреть").position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
                    map.addMarker(new MarkerOptions().title(name[i]).position(new LatLng(xx[i],yy[i])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
                    list.put(new LatLng(xx[i],yy[i]), i);
                    }
                    }
                //map.addMarker(someone);
            }
      }



      private String formatLocation(Location location) {
            if (location == null)
              return "";
            return String.format(
                "Coordinates: lat = %1$.4f, lon = %2$.4f, time = %3$tF %3$tT",
                location.getLatitude(), location.getLongitude(), new Date(
                    location.getTime()));



          }

      private void checkEnabled() {
            Log.d(" ...  ", "Enabled: "+ locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
            Log.d(" ...  ", "Enabled: "+ locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));

                      }


      private void frnd_name(final long vkid){
          ID = vkid;
          Thread getName = new Thread(new Runnable(){
                @Override
                public void run(){
                    JSONParser jsonParser = new JSONParser();
                    JSONObject json = jsonParser.getJSONFromUrl("http://api.vk.com/method/users.get?user_id=" + ID);

                    JSONArray array = null;
                  try {
                    array = json.getJSONArray("response");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                  for (int i = 0; i < array.length(); i++){
                    try {
                        JSONObject around = array.getJSONObject(i);
                        String nameFrnd = around.getString("first_name");
                        nameFrnd = nameFrnd + " " + around.getString("last_name");
                        nm = nameFrnd;
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                  }

                }
            });
          getName.start();
          if (getName.getState() == Thread.State.TERMINATED){
              for (int i = 0; i < name.length; i++){
                  name[i] = nm;
              }
          }

      }   

}

1 个答案:

答案 0 :(得分:0)

您正在

中添加标记
    private void showLocation(Location location) {
}

您正在通过位置监听器调用 showLocation() 方法...

只有当您要求位置管理员提供更新时才会触发位置监听器,这意味着您需要发表声明......

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            1000 * 10, 10, locationListener);

由于您正在初始化位置管理器以使用 onResume 方法提供更新,因此在调用 onResume 方法......

您可以初始化位置管理器,以便在 onStart 方法中提供更新

@Override
    protected void onStart() {
        super.onStart();
        mLocationClient.connect();
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(provider, 0, 0, this);
    }

您无需编写 onResume() 方法..

希望这会对你有帮助.........!