如何通过http在地图上显示多个标记

时间:2014-11-13 22:30:41

标签: android

我想在我的数据库中显示多个具有纬度和经度值的标记,但问题是当条件为真时它只返回1或0(表示地图上只显示一个标记)plz给我一个解决方案如何在地图上用标记显示lat和lng的多个值

这是我的代码:

public class Map extends Activity implements OnClickListener  {
             TextView Test;

         public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maptest);

        status();

               }
     public void status() {
    int locationCount =locationCount() ;
    for(int i=0;i<locationCount;i++)
    {
     double Latt = Lat();
     double Lngg = Lng();

     Test=(TextView)findViewById(R.id.test);
     String lat = new Double(Latt).toString();
     String lng = new Double(Lngg).toString();
     Test.setText(lng+ lat);
    }

}


 public static String convertStreamToString(InputStream is) 
    {
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     StringBuilder sb = new StringBuilder();

     String line = null;
     try {
      while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
      }
     } 
     catch (IOException e) {
      e.printStackTrace();
     } 
     finally {
      try {
       is.close();
      } catch (IOException e) {
    e.printStackTrace();
      }
     }
     return sb.toString();
    }

      public static double Lng()
        {
    try
    {
        DefaultHttpClient httpClient=new DefaultHttpClient();

        //Connect to the server
        HttpGet httpGet=new HttpGet("http://10.0.2.2:51220/Service1.svc/Lng");
      //Get the response
      HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
         InputStream stream=httpEntity.getContent();

         //Convert the stream to readable format
            String result= convertStreamToString(stream);

            if(result.charAt(1)=='1')
            {
             return 1;
            }
            else
            {
             return 0;
            }
     }
     catch(Exception e)
     {
      return 0;
     }

    }
     public static double Lat()
       {
    try
    {
        DefaultHttpClient httpClient=new DefaultHttpClient();

        //Connect to the server
        HttpGet httpGet=new HttpGet("http://10.0.2.2:51220/Service1.svc/Lat");
      //Get the response
      HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
         InputStream stream=httpEntity.getContent();

         //Convert the stream to readable format
            String result= convertStreamToString(stream);

            if(result.charAt(1)=='1')
            {
             return 1;
            }
            else
            {
             return 0;
            }
     }
     catch(Exception e)
     {
      return 0;
     }

    }

    public static int locationCount()
    {
    try
    {
        DefaultHttpClient httpClient=new DefaultHttpClient();

        //Connect to the server
        HttpGet httpGet=new HttpGet("http://10.0.2.2:51220/Service1.svc/locationCount");
      //Get the response
      HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
         InputStream stream=httpEntity.getContent();

         //Convert the stream to readable format
            String result= convertStreamToString(stream);

            if(result.charAt(1)=='1')
            {
             return 1;
            }
            else
            {
             return 0;
            }
     }
     catch(Exception e)
     {
      return 0;
     }

    }

   }`

EDIT1

好的,这是10.0.2.2:51220/Service1.svc/getLat

的输出
output:
<ArrayOfTrafficConditions>
<TrafficConditions>
<Lat>27.0006748</Lat>
<Latitude>27.0006748</Latitude>
</TrafficConditions>
<TrafficConditions>
<Lat>64.700064</Lat>
<Latitude>64.700064</Latitude>
</TrafficConditions></ArrayOfTrafficConditions>

这是webserivce的c#代码

namespace JSONSample
     {
public class DataAccess
{
    SqlConnection con;
    public DataAccess()
    {
        con = new SqlConnection("Data Source=SE7EN-PC;Initial Catalog=Demo;Integrated Security=True");
    }

      public List<TrafficConditions> getLat()
    {
        List<TrafficConditions> Lat= new List<TrafficConditions>();

    {
        con.Open();
        SqlCommand command = new SqlCommand("SELECT DISTINCT Latitude FROM TrafficConditions ", con);
        SqlDataReader reader = command.ExecuteReader();
           while (reader.Read())
            {
                TrafficConditions loc = new TrafficConditions();
                loc.Latitude = Convert.ToDouble(reader["Latitude"]);

                Lat.Add(loc);
            }
            return Lat.ToList();
        }
    }

      public List<Conditions> getLng()
      {
          List<Conditions> Lng = new List<Conditions>();

          {
              con.Open();
              SqlCommand command = new SqlCommand("SELECT DISTINCT Longitude FROM TrafficConditions", con);
              SqlDataReader reader = command.ExecuteReader();
              while (reader.Read())
              {
                  Conditions loc = new Conditions();

                  loc.Longitude = Convert.ToDouble(reader["Longitude"]);
                  Lng.Add(loc);
              }
              return Lng.ToList();
          }
      }

我只想将lat long值传递给我的Android应用程序而不是整个json值

EDIT2

抱歉这是我实际的地图活动代码

public class MapActivity extends FragmentActivity {

GoogleMap map;
ArrayList<LatLng> markerPoints;
ArrayList<LatLng> marker;
StatusClass gsp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);

    // Initializing 
    markerPoints = new ArrayList<LatLng>();
    marker = new ArrayList<LatLng>();

    // Getting reference to SupportMapFragment of the activity_main
    SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting Map for the SupportMapFragment
    map = fm.getMap();      

    if(map!=null){

        // Enable MyLocation Button in the Map
        map.setMyLocationEnabled(true); 

         Get();
    }

    }




     public void Get() {
         Calendar c1 = Calendar.getInstance();
            SimpleDateFormat sdf1 = new SimpleDateFormat("d/M/yy h:m:s a");
            String strdate1 = sdf1.format(c1.getTime());


            GPSTracker gps = new GPSTracker(MapActivity.this);
            gps.canGetLocation();
                double Latitude = gps.getLatitude();
                double Longitude = gps.getLongitude();



            // Adding new item to the ArrayList
            markerPoints.add(new LatLng(Latitude,Longitude ));              

            // Creating MarkerOptions
            MarkerOptions options = new MarkerOptions();

            // Setting the position of the marker
            options.position(new LatLng(Latitude,Longitude ));
            options.title(strdate1+"");
            //options.snippet(Timestemp()+ " last updated");



            /** 
             * For the start location, the color of marker is GREEN and
             * for the end location, the color of marker is RED.
             */
            if(markerPoints.size()>=1){
                      options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            }


            // Add new marker to the Google Map Android API V2
            map.addMarker(options);


                }





        public ArrayList<Double> FromJSONtoArrayListLat() {
            ArrayList<Double> ListLat = new ArrayList<Double>();

            try {

                // Replace it with your own WCF service path
                URL json = new URL("http://10.0.2.2:51220/Service1.svc/getLat");
                URLConnection jc = json.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

                String line = reader.readLine();

                JSONObject jsonResponse = new JSONObject(line);
                JSONArray jsonArray = jsonResponse.getJSONArray("getLat");

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jObject = (JSONObject)jsonArray.get(i);

                    // "FullName" is the property of .NET object spGetPersonsResult, 
                    // and also the name of column in SQL Server 2008
                    ListLat.add(jObject.getDouble("Latitude"));

                }

                reader.close();

            } catch(Exception e){
                Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
            }

            return ListLat;
        }

        public ArrayList<Double> FromJSONtoArrayListLng() {
            ArrayList<Double> ListLng = new ArrayList<Double>();

            try {

                // Replace it with your own WCF service path
                URL json = new URL("http://10.0.2.2:51220/Service1.svc/getLng");
                URLConnection jc = json.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

                String line = reader.readLine();

                JSONObject jsonResponse = new JSONObject(line);
                JSONArray jsonArray = jsonResponse.getJSONArray("getLng");

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jObject = (JSONObject)jsonArray.get(i);

                    // "FullName" is the property of .NET object spGetPersonsResult, 
                    // and also the name of column in SQL Server 2008
                    ListLng.add(jObject.getDouble("Longitude"));

                }

                reader.close();

            } catch(Exception e){
                Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
            }

            return ListLng;
        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

现在使用此代码如何获取经度和纬度值以显示多个标记?你能帮我吗

2 个答案:

答案 0 :(得分:0)

首先,请使用像这样的MapActivity:

public class Map extends MapActivity implements LocationListener 
{
    gMapView = (MapView) findViewById(R.id.mapview);

    //This is how you get a position on the map.
    p = new GeoPoint((int) (latitude * 1000000), (int) (longitude * 1000000));

    gMapView.setSatellite(true);//set the view type of your map.

    // Add a location mark or overlays here like so . . . 
    myLocationOverlay = new MyLocationOverlay2();

    //This is the list of overlays.
    List<Overlay> list = gMapView.getOverlays();

    //Add myLocationOverlay in the list.
    list.add(myLocationOverlay); 

    // and so on ...
}

我使用MyLocationOverlay2用叠加层更新我的地图。但您可以使用它来添加或更新标记。举个例子,这是该类的代码:

protected class MyLocationOverlay2 extends com.google.android.maps.Overlay
    {
    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
            {
                //-------------------------------------
                //  Drawing the path
                //-------------------------------------

                   //If the location has at least 2 points in the array.
                   if(geoPointCollection.size()>=3)
                    {
                        //Configuring the paint brush    
                        Paint mPaint = new Paint();
                        mPaint.setDither(true);
                        mPaint.setColor(Color.argb(255, 255, 72, 0));
                        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
                        mPaint.setStrokeJoin(Paint.Join.ROUND);
                        mPaint.setStrokeCap(Paint.Cap.ROUND);
                        mPaint.setStrokeWidth(5);

                        //-------------------------------------
                        //  Drawing the paths
                        //-------------------------------------
                        int temp = 0;
                        Point tempp = new Point();
                        for(int i = 1; i < geoPointCollection.size()-1;i++)
                        {

                            Point point1 = new Point();
                            Point point2 = new Point();
                            Path path    = new Path();

                            mapView.getProjection().toPixels(geoPointCollection.get(i), point1);
                            mapView.getProjection().toPixels(geoPointCollection.get(i+1), point2);

                            path.moveTo(point1.x, point1.y);
                            path.lineTo(point2.x,point2.y);

                            canvas.drawPath(path, mPaint);
                            temp = i+1;
                            tempp = point1;
                        }
                            Paint paint = new Paint();
                            super.draw(canvas, mapView, shadow);
                            // Converts lat/lng-Point to OUR coordinates on the screen.

                            mapView.getProjection().toPixels(geoPointCollection.get(temp), tempp);

                            paint.setStrokeWidth(1);
                            paint.setARGB(255, 255, 255, 255);
                            paint.setStyle(Paint.Style.STROKE);

                            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.indicator);

                            canvas.drawBitmap(bmp, tempp.x-28, tempp.y-28, paint);
                    }
                   else
                   {
                    //-------------------------------------
                    //Drawing the Crosshair on the map.
                    //-------------------------------------
                    Paint paint = new Paint();
        super.draw(canvas, mapView, shadow);
        // Converts lat/lng-Point to OUR coordinates on the screen.
        Point myScreenCoords = new Point();
        mapView.getProjection().toPixels(p, myScreenCoords);

        paint.setStrokeWidth(1);
        paint.setARGB(255, 255, 255, 255);
        paint.setStyle(Paint.Style.STROKE);

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.indicator);

        canvas.drawBitmap(bmp, myScreenCoords.x-28, myScreenCoords.y-28, paint);
                   }

                    return true;
    }
}

您也可以这样做,只需更新以特定间隔运行的处理程序中的地图叠加层。

答案 1 :(得分:0)

好的,这是10.0.2.2:51220/Service1.svc/getLat

的输出
output:
<ArrayOfTrafficConditions>
<TrafficConditions>
<Lat>27.0006748</Lat>
<Latitude>27.0006748</Latitude>
</TrafficConditions>
<TrafficConditions>
<Lat>64.700064</Lat>
<Latitude>64.700064</Latitude>
</TrafficConditions></ArrayOfTrafficConditions>

这是webserivce的c#代码

namespace JSONSample
     {
public class DataAccess
{
    SqlConnection con;
    public DataAccess()
    {
        con = new SqlConnection("Data Source=SE7EN-PC;Initial Catalog=Demo;Integrated Security=True");
    }

      public List<TrafficConditions> getLat()
    {
        List<TrafficConditions> Lat= new List<TrafficConditions>();

    {
        con.Open();
        SqlCommand command = new SqlCommand("SELECT DISTINCT Latitude FROM TrafficConditions ", con);
        SqlDataReader reader = command.ExecuteReader();
           while (reader.Read())
            {
                TrafficConditions loc = new TrafficConditions();
                loc.Latitude = Convert.ToDouble(reader["Latitude"]);

                Lat.Add(loc);
            }
            return Lat.ToList();
        }
    }

      public List<Conditions> getLng()
      {
          List<Conditions> Lng = new List<Conditions>();

          {
              con.Open();
              SqlCommand command = new SqlCommand("SELECT DISTINCT Longitude FROM TrafficConditions", con);
              SqlDataReader reader = command.ExecuteReader();
              while (reader.Read())
              {
                  Conditions loc = new Conditions();

                  loc.Longitude = Convert.ToDouble(reader["Longitude"]);
                  Lng.Add(loc);
              }
              return Lng.ToList();
          }
      }

我只想将lat long值传递给我的Android应用程序而不是整个json值