2013-07-18 2 views
0

Я полностью расстроен - у меня есть простое приложение для Android, и я попытался получить направление, используя API-интерфейс google maps, после рендеринга карты. Ответ XML, который я получаю, REQUEST_DENIED.Google Direction API -REQUEST_DENIED

Пожалуйста, помогите !!!. Я не специалист в андроиде и до сих пор изучают трюки ... Это требование hptts, что выходит: -

https://maps.googleapis.com/maps/api/directions/xml?origin=losgatos&destination=cupertino&sensor=false

я отправил этот вопрос и раньше, но не получил никакого ответа. заранее.

Мой полный код: - (Main класс).

public class MainActivity extends FragmentActivity { 
MapDirection md ; 
LatLng fromPosition; 
LatLng toPosition; 
ArrayList<LatLng>ToFrom; 
Document doc; 
ArrayList<LatLng> directionPoint; 
PolylineOptions rectLine; 
//Intent MapProcessIntent; 
ArrayList<LatLng> markerpoints; 
LocationManager lm; 
GoogleMap map; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //setContentView(R.layout.main); 

    setContentView(R.layout.activity_main); 
    markerpoints = new ArrayList<LatLng>(); 

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    //LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); 
    boolean enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_HIGH); 
    String provider = lm.getBestProvider(criteria, true); 
    Location currentLocation = lm.getLastKnownLocation(provider); 

    SupportMapFragment fm =(SupportMapFragment)this.getSupportFragmentManager().findFragmentById(R.id.map); 
    map = fm.getMap(); 
    if (map != null){ 
     map.setMyLocationEnabled(true); 
     CameraPosition cameraPosition= new CameraPosition.Builder().target(new LatLng(currentLocation.getLatitude(), 
       currentLocation.getLongitude())).zoom(13).build(); 
     map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

    } 

    LatLng fromPosition = new LatLng(37.258507,-121.967533); 
    LatLng toPosition = new LatLng(37.236064,-121.961595); 
    map.addMarker(new MarkerOptions().position(fromPosition).title("Start")); 
    map.addMarker(new MarkerOptions().position(toPosition).title("End")); 




    //TextView textview = (TextView)this.findViewById(R.id.mainstring); 
    //textview.setText("making the web service call.."); 



    //fromPosition = new LatLng(37.258507,-121.967533); 
    //toPosition = new LatLng(37.236064,-121.961595); 
    ToFrom = new ArrayList<LatLng>(); 
    ToFrom.add(fromPosition); 
    ToFrom.add(toPosition); 
    //MapProcessIntent = new Intent(this, MapProcess.class); 
    //Document doc = md.getDocument(fromPosition, toPosition, MapDirection.MODE_DRIVING); 
    /*if (doc.hasChildNodes()== true) 
    { 
     System.out.println("This document has child nodes.."); 
    } 
    if (doc != null){ 
    //ArrayList<LatLng> directionPoint = md.getDirection(doc); 
    //PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED); 

    for(int i = 0 ; i < directionPoint.size() ; i++) {   
    rectLine.add(directionPoint.get(i)); 
    }*/ 
    MakeWebCall mwc = new MakeWebCall(); 
    mwc.execute(ToFrom); 


} 

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



private class MakeWebCall extends AsyncTask<ArrayList<LatLng>, Void, Document> 
{ 

@Override 
protected Document doInBackground(ArrayList<LatLng>...list) { 
     Document d = null; 
     LatLng From = (LatLng)list[0].get(0); 
     LatLng To= (LatLng)list[0].get(1); 
    // params comes from the execute() call: params[0] is the list 
    try { 
     md= new MapDirection(); 
     d = md.getDocument(From, To, MapDirection.MODE_DRIVING); 


    } catch (Exception e) { 
     System.out.println(" Some error "+ e.getMessage()); 

    } 
    return d; 
    } 
// onPostExecute displays the results of the AsyncTask. 
@Override 
protected void onPostExecute(Document doc) { 
    if (doc !=null){ 
     directionPoint = md.getDirection(doc); 
     if (directionPoint.isEmpty()== false){ 
      rectLine = new PolylineOptions().width(3).color(Color.RED); 
      for(int i = 0 ; i < directionPoint.size() ; i++) {   
       rectLine.add(directionPoint.get(i)); 
      } 

      if (rectLine !=null){ 
        Polyline pl= map.addPolyline(rectLine); 
        if (pl != null){ 
         pl.setVisible(true); 
         System.out.println(" I GOT IT"); 
        } 
      //String polylineStr = "POLYLINE"; 

       //MapProcessIntent.putExtra(polylineStr, rectLine); 
       //startActivity(MapProcessIntent); 
     } 
    } 
    else 
    { 
     System.out.println(" document is empty"); 
    } 


} 
} 
} 
} 

Мой файл MapDirection (который делает вызов веб-службы :)

import java.io.IOException; 
import java.io.InputStream; 
import java.net.URLEncoder; 
import java.util.ArrayList; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.BasicHttpContext; 
import org.apache.http.protocol.HttpContext; 
import org.w3c.dom.Document; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.SAXException; 
import org.xml.sax.SAXParseException; 



import android.os.StrictMode; 
import android.util.Log; 

import com.google.android.gms.maps.model.LatLng; 

class MapDirection { 
public final static String MODE_DRIVING = "driving"; 
public final static String MODE_WALKING = "walking"; 

public MapDirection() { } 

public Document getDocument(LatLng start, LatLng end, String mode) { 
    String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
      + "origin=" + start.latitude + "," + start.longitude 
      + "&destination=" + end.latitude + "," + end.longitude 
      + "&sensor=false&units=metric&mode=driving"; 

    try { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     String hosturl="https://maps.googleapis.com/maps/api/directions/xml?"; 
     String newstring = "origin=" + start.latitude + "," + start.longitude 
     + "&destination=" + end.latitude + ","+ end.longitude + "&sensor=true"; 
     //37.255666,-121.967683 
     //37.258507,-121.967533 
     //String newstring = "origin=37.2345487,-121.5840723&destination=37.236064,-121.961595&sensor=true"; 
     String newurl = URLEncoder.encode(newstring, "UTF-8"); 
     String finalurl = hosturl + newurl; 
     System.out.println("web service call: "+finalurl); 
     HttpPost httpPost = new HttpPost(finalurl); 
     HttpResponse response = httpClient.execute(httpPost, localContext); 
     InputStream in = response.getEntity().getContent(); 
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = builder.parse(in); 
     System.out.println(" Returned valid document"); 
     return doc; 
    } catch (IllegalArgumentException e) { 

     System.out.println(" Web service returned IllegalArgumentException:"+ e.getMessage()); 
     e.printStackTrace(); 
     return null; 
    } 
    catch(IOException f){ 
     System.out.println(" Web service returned IOException:"+ f.getMessage()); 
     f.printStackTrace(); 
     return null; 
    } 
    catch(IllegalStateException g){ 
     System.out.println(" Web service returned IllegalStateException:"+ g.getMessage()); 
     g.printStackTrace(); 
     return null; 
    } 
    catch(ParserConfigurationException h){ 
     System.out.println(" Web service returned ParserConfigurationException:"+ h.getMessage()); 
     h.printStackTrace(); 
     return null; 
    } 
    catch(SAXException i){ 
     System.out.println(" Web service returned SAXException:"+ i.getMessage()); 
     i.printStackTrace(); 
     return null; 
    } 

} 

public String getDurationText (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("duration"); 
    Node node1 = nl1.item(0); 
    NodeList nl2 = node1.getChildNodes(); 
    Node node2 = nl2.item(getNodeIndex(nl2, "text")); 
    Log.i("DurationText", node2.getTextContent()); 
    return node2.getTextContent(); 
} 

public int getDurationValue (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("duration"); 
    Node node1 = nl1.item(0); 
    NodeList nl2 = node1.getChildNodes(); 
    Node node2 = nl2.item(getNodeIndex(nl2, "value")); 
    Log.i("DurationValue", node2.getTextContent()); 
    return Integer.parseInt(node2.getTextContent()); 
} 

public String getDistanceText (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("distance"); 
    Node node1 = nl1.item(0); 
    NodeList nl2 = node1.getChildNodes(); 
    Node node2 = nl2.item(getNodeIndex(nl2, "text")); 
    Log.i("DistanceText", node2.getTextContent()); 
    return node2.getTextContent(); 
} 

public int getDistanceValue (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("distance"); 
    Node node1 = nl1.item(0); 
    NodeList nl2 = node1.getChildNodes(); 
    Node node2 = nl2.item(getNodeIndex(nl2, "value")); 
    Log.i("DistanceValue", node2.getTextContent()); 
    return Integer.parseInt(node2.getTextContent()); 
} 

public String getStartAddress (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("start_address"); 
    Node node1 = nl1.item(0); 
    Log.i("StartAddress", node1.getTextContent()); 
    return node1.getTextContent(); 
} 

public String getEndAddress (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("end_address"); 
    Node node1 = nl1.item(0); 
    Log.i("StartAddress", node1.getTextContent()); 
    return node1.getTextContent(); 
} 

public String getCopyRights (Document doc) { 
    NodeList nl1 = doc.getElementsByTagName("copyrights"); 
    Node node1 = nl1.item(0); 
    Log.i("CopyRights", node1.getTextContent()); 
    return node1.getTextContent(); 
} 

public ArrayList<LatLng> getDirection (Document doc) { 
    NodeList nl1, nl2, nl3,statusList; 
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>(); 
    statusList = doc.getElementsByTagName("status"); 
    if (statusList.getLength()> 0){ 
     System.out.println(" Status result of XML response for direction API:"+statusList.item(0).getTextContent()); 
    } 
    nl1 = doc.getElementsByTagName("step"); 
    if (nl1.getLength() > 0) { 
     for (int i = 0; i < nl1.getLength(); i++) { 
      Node node1 = nl1.item(i); 
      nl2 = node1.getChildNodes(); 

      Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); 
      nl3 = locationNode.getChildNodes(); 
      Node latNode = nl3.item(getNodeIndex(nl3, "lat")); 
      double lat = Double.parseDouble(latNode.getTextContent()); 
      Node lngNode = nl3.item(getNodeIndex(nl3, "lng")); 
      double lng = Double.parseDouble(lngNode.getTextContent()); 
      listGeopoints.add(new LatLng(lat, lng)); 

      locationNode = nl2.item(getNodeIndex(nl2, "polyline")); 
      nl3 = locationNode.getChildNodes(); 
      latNode = nl3.item(getNodeIndex(nl3, "points")); 
      ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); 
      for(int j = 0 ; j < arr.size() ; j++) { 
       listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); 
      } 

      locationNode = nl2.item(getNodeIndex(nl2, "end_location")); 
      nl3 = locationNode.getChildNodes(); 
      latNode = nl3.item(getNodeIndex(nl3, "lat")); 
      lat = Double.parseDouble(latNode.getTextContent()); 
      lngNode = nl3.item(getNodeIndex(nl3, "lng")); 
      lng = Double.parseDouble(lngNode.getTextContent()); 
      listGeopoints.add(new LatLng(lat, lng)); 
     } 
    } 

    return listGeopoints; 
} 

private int getNodeIndex(NodeList nl, String nodename) { 
    for(int i = 0 ; i < nl.getLength() ; i++) { 
     if(nl.item(i).getNodeName().equals(nodename)) 
      return i; 
    } 
    return -1; 
} 

private ArrayList<LatLng> decodePoly(String encoded) { 
    ArrayList<LatLng> poly = new ArrayList<LatLng>(); 
    int index = 0, len = encoded.length(); 
    int lat = 0, lng = 0; 
    while (index < len) { 
     int b, shift = 0, result = 0; 
     do { 
      b = encoded.charAt(index++) - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 
     int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
     lat += dlat; 
     shift = 0; 
     result = 0; 
     do { 
      b = encoded.charAt(index++) - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 
     int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
     lng += dlng; 

     LatLng position = new LatLng((double) lat/1E5, (double) lng/1E5); 
     poly.add(position); 
    } 
    return poly; 
} 
} 

Позвольте мне опубликовать мой файл манифеста тоже ..

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.menonmatics.mapapplication" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="9" 
    android:targetSdkVersion="16" /> 
<uses-permission android:name="android.permission.INTERNET"/> 
<permission 
    android:name="com.menonmatics.mapapplication.permission.MAPS_RECEIVE" 
    android:protectionLevel="signature" /> 
<uses-permission android:name="com.menonmatics.mapapplication.permission.MAPS_RECEIVE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission  android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true"/> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="com.menonmatics.mapapplication.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name=".MapProcess" 
android:label="Map Rendering"> 
<intent-filter> 
    <category android:name="android.intent.category.LAUNCHER" /> 
</intent-filter> 
</activity> 
    <meta-data 
android:name="com.google.android.maps.v2.API_KEY" 
android:value="<tooitout"/> 
</application> 

</manifest> 

ответ

-1

Проверить этот пример google direction

попробуйте следующее:

try { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     String hosturl="https://maps.googleapis.com/maps/api/directions/xml?"; 
     String newstring = "origin=" + start.latitude + "," + start.longitude 
     + "&destination=" + end.latitude + ","+ end.longitude + "&sensor=true"; 
     //37.255666,-121.967683 
     //37.258507,-121.967533 
     //String newstring = "origin=37.2345487,-121.5840723&destination=37.236064,-121.961595&sensor=true"; 
     //String newurl = URLEncoder.encode(newstring, "UTF-8"); 
     String finalurl = hosturl + newstring; 
     System.out.println("web service call: "+finalurl); 
     HttpPost httpPost = new HttpPost(finalurl); 
     HttpResponse response = httpClient.execute(httpPost, localContext); 
     InputStream in = response.getEntity().getContent(); 
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = builder.parse(in); 
     System.out.println(" Returned valid document"); 
     return doc; 
    } 
+0

Спасибо, Srikanth. оцените ваш быстрый ответ. что не так со следующим кодом, который я написал: - – sunny

+0

Мне действительно нужно использовать API google places ?. Не могу ли я просто напрямую использовать вызов веб-сервисов и проанализировать ответ xml. Я использую старый API карт google, который не был интегрирован с местами. Есть ли проблема совместимости с веб-сервисами направлений и Google Map api, которые я использую, в результате чего REQUEST_DENIED ?. – sunny

+0

Я просто попробовал эту ссылку, это выглядит нормально –

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