JSON

2016-09-12 1 views
0
마커지도에서 표시되지

를 이용하여지도 표시를 플롯 없었던 JSON 데이터 완전히 미세 내가 debugging.but 마커지도JSON

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 
public GoogleMap mMap; 

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


public void onMapSearch (View view) throws IOException { 

    //hide button when button is pressed 
    InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); 
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 

    //preview the entered address as an Tost in bar 
    EditText locationSearch = (EditText) findViewById(R.id.editText); 
    String location = locationSearch.getText().toString(); 

    //this will animate camera and zoom 12.0f 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f)); 



    //further address search codes 
    List<Address> addressList = null; 

    //if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app 
    if (locationSearch.getText().toString().equals("")){ 
     Toast.makeText(this,"Bitch please enter A Value",Toast.LENGTH_LONG).show(); 
    } 
    else { 

     //process of exception handling and finding location 
     if (location != null || !location.equals("")) { 
      Geocoder geocoder = new Geocoder(this); 
      try { 
       addressList = geocoder.getFromLocationName(location, 1); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       } 
      //if address is greater than one then these processes will happen 

      if(addressList.size()>0) { 
       Address address = addressList.get(0); 
       LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); 
       mMap.addMarker(new MarkerOptions() 
         .position(latLng) 
         .title(location + " is Here- ") 
         .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); 
       mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 

       Toast.makeText(this, location+" is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG) 
         .show(); //popup type to show entered data 
      } 
      else { 
       //process where entered entry will not gonna find , this will gonna a toast to show popup 

       Toast.makeText(this,"Entered Address Not Found", Toast.LENGTH_LONG).show(); 

      } 
     } 

    } 
} 


private class RetriveMarkerTask extends AsyncTask<StringBuilder,Void,StringBuilder> { 
    private Context context; 
    private String jsonData; 

    public RetriveMarkerTask(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected StringBuilder doInBackground(StringBuilder... stringBuilders) { 
     android.os.Debug.waitForDebugger(); 

     HttpURLConnection conn = null; 
     final StringBuilder json = new StringBuilder(); 
     try { 
      //connect to the web service 
      URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations"); 
      conn = (HttpURLConnection) url.openConnection(); 
      InputStreamReader in = new InputStreamReader(conn.getInputStream()); 
      //This will read the json data into string builder 
      int read; 
      char[] buff = new char[1024]; 
      while ((read = in.read(buff)) != -1) { 
       json.append(buff, 0, read); 
      } 
      this.jsonData = new String(buff); 
     } catch (IOException e) { 
      return null; 
     } catch (Exception ex) { 
      return null; 
     } finally { 
      if (conn != null) { 
       conn.disconnect(); 
      } 
      return json; 
     } 
    } 

    @Override 
    protected void onPostExecute(StringBuilder stringBuilder) { 
     super.onPostExecute(stringBuilder); 
     try { 
      ((MapsActivity)context).createMarkerFromJson(this.jsonData); 
     }catch (JSONException e){ 
      e.printStackTrace(); 
     } 
    } 
} 



void createMarkerFromJson (String json) throws JSONException { 
    // de-derialize the json string into an array of objects 


     JSONArray jsonArray = new JSONArray(json); 
     for (int i =0; i<jsonArray.length(); i++){ 
      //create marker of each place in the json data 
      JSONObject jsonObject = jsonArray.getJSONObject(i); 
      String placeName = jsonObject.getString("name"); 
      String placeAddress = jsonObject.getString("address"); 
      double latitude = jsonObject.getJSONArray("latlang").getDouble(0); 
      double longitude = jsonObject.getJSONArray("latlang").getDouble(1); 
      LatLng loc = new LatLng(latitude, longitude); 
      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13)); 
      mMap.addMarker(new MarkerOptions() 
        .title(placeName) 
        .snippet(placeAddress) 
        .position(loc) 
      ); 
     } 

    } 

//OnReady map starts here when we can enter or add Marker to the map 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    try { 
     RetriveMarkerTask markerTask = new RetriveMarkerTask(this); 
     markerTask.execute(); 
    }catch (Exception e){ 
     Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show(); 
    } 

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission 
      (this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     // int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    //tool bar and other tool related on map uiSettings 
    mMap.setMyLocationEnabled(true); 
    mMap.getUiSettings().setZoomControlsEnabled(true); 
    mMap.getUiSettings().setMapToolbarEnabled(true); 
    mMap.getUiSettings().setMyLocationButtonEnabled(true); 

} 

}에 도시되어 있지 않을 때 볼 수있는

+0

당신은 Lat 및 Lng를 개별적으로 또는 하나의 LatLng로 받고 있습니까? 의미는 Lat = "x"이고 Lng = "y"또는 LatLng = "xy"입니다. –

+0

점점 ... 개별적으로 –

답변

0

컨텍스트를 작업에 전달한 다음 컨텍스트를 캐스팅하여 함수를 호출하는 대신 생성자에서 mMap을 전달한 다음 createMarkerFromJson 함수를 AsyncTask 클래스 내부로 이동하는 것이 좋습니다. Json 데이터가 올바르게 반환되면 마커가 올바른 것으로 추가되었는지 확인하는 데 도움이됩니다. moveCamera에 대한 호출이 발생합니까?

+0

동일한 작업이 수행되지 않습니다 .... 내 moveCamera 호출이 발생하지 않습니다. –

+0

더하기 PostExecute 더하기 토스트를 보여 드릴 수 없습니다 ... –

+0

수퍼 클래스 onPostExecute에 대한 호출을 제거하십시오. 거기에있을 필요가 없습니다. 마커 생성을 수행하기도 전에 아마도 onPostExecute가 충돌 할 것입니다. – HollywoodCurls