0

Моя цель - нарисовать маркеры на основе координат GPS, полученных с сервера WAMP. Я не могу нарисовать маркеры, что я должен улучшить в своем коде, чтобы сделать это?Извлечь данные из базы данных сервера SQL WAMP в приложение для Android

Ниже приведен код отвечает получение данных из базы данных, работающих на сервере WAMP и рисование маркеров на карте:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 
    private GoogleMap mMap; 
    private RequestQueue requestQueue; 
    private double lat; 
    private double lon; 
    private int flag; 
    private String showUrl = "http://<<LOCAL-IP-ADDRESS>/directory/showSensor.php"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready 
     // to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     requestQueue = Volley.newRequestQueue(getApplicationContext()); 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 
          JSONArray sensorLocations = response.getJSONArray("Sensor Locations"); 

          for (int i = 0; i < sensorLocations.length(); i++) { 
           JSONObject sensorLocation = sensorLocations.getJSONObject(i); 
           String latitude = sensorLocation.getString("lat"); 
           String longitude = sensorLocation.getString("long"); 
           String flg = sensorLocation.getString("flag"); 

           if (flag == 1) { 
            lat = Double.parseDouble(latitude); 
            lon = Double.parseDouble(longitude); 
            flag = 0; 
           } 
          } 
          ; 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
        } 
       }); 
     requestQueue.add(jsonObjectRequest); 
    } 

    /** 
    * Manipulates the map once available. This callback is triggered when the 
    * map is ready to be used. This is where we can add markers or lines, add 
    * listeners or move the camera. In this case, we just add a marker near 
    * Sydney, Australia. If Google Play services is not installed on the 
    * device, the user will be prompted to install it inside the 
    * SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     // Add a marker in Sydney and move the camera 
     LatLng sensor = new LatLng(lat, lon); 
     mMap.addMarker(new MarkerOptions().position(sensor).title(lat + "," + lon)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor)); 
    } 
} 

ответ

0

кажется, что метод onMapReady вызывается, прежде чем вы получите ответ от вашего сервер. Переместите код, чтобы запросить данные с вашего сервера до метода:

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    requestQueue = Volley.newRequestQueue(getApplicationContext()); 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, 
       showUrl, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 

       try { 
        JSONArray sensorLocations = response.getJSONArray("Sensor Locations"); 

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

         JSONObject sensorLocation = sensorLocations.getJSONObject(i); 
         String latitude = sensorLocation.getString("lat"); 
         String longitude= sensorLocation.getString("long"); 
         String flg = sensorLocation.getString("flag"); 

         if(flag ==1) { 
          lat = Double.parseDouble(latitude); 
          lon = Double.parseDouble(longitude); 
          flag=0; 

          LatLng sensor = new LatLng(lat, lon); 
          mMap.addMarker(new MarkerOptions().position(sensor).title(lat+ " " + lon)); 
          mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor)); 
         } 
        } 

        ; 
       }catch(JSONException e){ 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 

      } 
     }); 
    requestQueue.add(jsonObjectRequest); 
} 
+0

Эй, парень, да! Он отлично работает :) спасибо. – Androider

+0

Несомненно! Я отметил это – Androider

Смежные вопросы