2016-09-14 28 views
0

我一直在試圖繪製標記使用json,但無法繪製它,onPostExecute我甚至無法顯示吐司,但拉特朗是單獨進來,我測試這隻使用3-4標記(JSON格式)以下 是一個JSON樣本 -無法繪製標記使用json和onPostExecute沒有響應

[{"name":"Thekha desi wine","address":"SR Complex, Naya Bans, Sector 15, Noida","latlang":["28.582122","77.313233"]},{"name":"Thekha desi wine","address":"SR Complex, Naya Bans, Sector 15, Noida","latlang":["28.582122","77.313233"]},{"name":"Thekha desi wine","address":"SR Complex, Naya Bans, Sector 15, Noida","latlang":["28.582122","77.313233"]}] 

mapsActivity代碼:

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<String,Void,String> { 
    private Context context; 
    private GoogleMap gMap; 

    public RetriveMarkerTask(Context context, GoogleMap mMap) { 
     this.context = context; 
     this.gMap = mMap; 
    } 

    protected void onPreExecute(){ 
     Toast.makeText(context, "pre execute", Toast.LENGTH_LONG).show(); 
    } 

    protected String doInBackground(String... markerGetUrl) { 
     android.os.Debug.waitForDebugger(); 

     HttpURLConnection conn = null; 
     final StringBuilder json = new StringBuilder(); 
     int read; 
     char[] buff = new char[1024]; 
     try { 
      //connect to the web service 
      URL url = new URL(markerGetUrl[0]); 
      conn = (HttpURLConnection) url.openConnection(); 
      //This will read the json data into string builder 
      InputStreamReader in = new InputStreamReader(conn.getInputStream()); 
      while ((read = in.read(buff)) != -1) { 
       json.append(buff, 0, read); 
      } 
     } catch (IOException e) { 
      return null; 
     } catch (Exception ex) { 
      return null; 
     } finally { 
      if (conn != null) { 
       conn.disconnect(); 
      } 
     } 
     String markersJson = new String(buff).trim(); 
     return markersJson; 
    } 

    protected void onPostExecute(String markers) { 

     Toast.makeText(context, "Post Execute", Toast.LENGTH_LONG).show(); 

     LatLng dwarka = new LatLng(28.570317,77.32182); 
     gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13)); 
     gMap.addMarker(
       new MarkerOptions() 
         .title("Wine Beer Liquor Shop, Sector 18, Noida") 
         .snippet("Sector 18, Near Centre Stage Mall, Noida") 
         .position(dwarka)); 
     /* 
     try { 
      JSONArray jsonArray = new JSONArray(markers); 
      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); 
       gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13)); 
       gMap.addMarker(new MarkerOptions() 
         .title(placeName) 
         .snippet(placeAddress) 
         .position(loc) 
       ); 
      } 
     }catch (JSONException e){ 
      e.printStackTrace(); 
     } 
     */ 
    } 
} 

//OnReady map starts here when we can enter or add Marker to the map 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    Toast.makeText(this, "On Map ready", Toast.LENGTH_LONG).show(); 
    mMap = googleMap; 

    try { 
     String url = new String("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations"); 
     RetriveMarkerTask markerTask = new RetriveMarkerTask(this, mMap); 
     markerTask.execute(url); 
    }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

爲什麼你有兩個問題發佈? http://stackoverflow.com/questions/39343995/android-studio-unable-to-plot-marker-using-json/39345189?noredirect=1#comment66054054_39345189 –

+0

我真的在爛攤子得不到答案,這個問題有一些不同代碼,如果你可以請回答我的問題 –

+0

@AmadYus先生請現在告訴我我現在怎麼顯示標記,爲什麼onPostExecute我無法顯示甚至烤麪包,提前致謝 –

回答

0

讓我們嘗試不OnMapReady() 試圖得到一些基本功能這樣的:

public class MapsActivity extends FragmentActivity { 
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); 
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap(); 

try { 
    String url = new String("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations"); 
    RetriveMarkerTask markerTask = new RetriveMarkerTask(this, mMap); 
    markerTask.execute(url); 
}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); 
} 

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<String,Void,String> { 
private Context context; 
private GoogleMap gMap; 

public RetriveMarkerTask(Context context, GoogleMap mMap) { 
    this.context = context; 
    this.gMap = mMap; 
} 

protected void onPreExecute(){ 
    Toast.makeText(context, "pre execute", Toast.LENGTH_LONG).show(); 
} 

protected String doInBackground(String... markerGetUrl) { 
    android.os.Debug.waitForDebugger(); 

    HttpURLConnection conn = null; 
    final StringBuilder json = new StringBuilder(); 
    int read; 
    char[] buff = new char[1024]; 
    try { 
     //connect to the web service 
     URL url = new URL(markerGetUrl[0]); 
     conn = (HttpURLConnection) url.openConnection(); 
     //This will read the json data into string builder 
     InputStreamReader in = new InputStreamReader(conn.getInputStream()); 
     while ((read = in.read(buff)) != -1) { 
      json.append(buff, 0, read); 
     } 
    } catch (IOException e) { 
     return null; 
    } catch (Exception ex) { 
     return null; 
    } finally { 
     if (conn != null) { 
      conn.disconnect(); 
     } 
    } 
    String markersJson = new String(buff).trim(); 
    return markersJson; 
} 

protected void onPostExecute(String markers) { 

    Toast.makeText(context, "Post Execute", Toast.LENGTH_LONG).show(); 

    LatLng dwarka = new LatLng(28.570317,77.32182); 
    gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13)); 
    gMap.addMarker(
      new MarkerOptions() 
        .title("Wine Beer Liquor Shop, Sector 18, Noida") 
        .snippet("Sector 18, Near Centre Stage Mall, Noida") 
        .position(dwarka)); 

} 
} 

} 
+0

getMap();和這個);顯示錯誤,請求我在此上添加onMapReady並getMap顯示無法解析方法 –

0

變化

// Obtain the SupportMapFragment and get notified when the map is ready to be used. 
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager() 
      .findFragmentById(R.id.safety_map)); 

我預計,這將很好地工作。祝你好運!