开发者

Android JavaScript Google Maps Issue (Dealer Location)

开发者 https://www.devze.com 2023-04-03 16:25 出处:网络
I am developing an application where basically, when a user clicks Dealer Location, it will load up Google maps and read a csv file with all dealer info - but display their closest or the closest to a

I am developing an application where basically, when a user clicks Dealer Location, it will load up Google maps and read a csv file with all dealer info - but display their closest or the closest to a post code they enter. I have entered the code i have below which should pull the dealer list, but can anyone take a look and let me know if they see any obvious errors?

package com.huyndai.i40.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.huyndai.i40.R;
import com.huyndai.i40.model.Dealer;

public class Util {
 public static final String TESTDRIVE_TEL = "01614523170";
 public static final String TAG = "HUYNDAI";
 private static Collection dealerList = null;
 private static Location curentLocation;

 public static Collection getDealerList(Context context) {
   if (dealerList != null) {
    return dealerList;
   } // read from cvs dealerList = new ArrayList(); InputStream inputStream = context.getResources().openRawResource(R.raw.dealers_list); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String reader = ""; try { in.readLine();// skip header while ((reader = in.readLine()) != null) { String[] RowData = reader.split(";"); // DEALER;ROAD;ADDRESS_2;TOWN;POSTCODE;TELEPHONE;LATITUDE;LONGTITUDE if (RowData.length >= 8) { Dealer d = new Dealer(); d.name = RowData[0]; d.road = RowData[1]; d.address = RowData[2]; d.town = RowData[3]; d.postcode = RowData[5]; d.phone = RowData[6]; //d.lat = (int) (Double.valueOf(RowData[6]) * 1E6); //d.lon = (int) (Double.valueOf(RowData[7]) * 1E6); dealerList.add(d); } } in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dealerList; }

   public static Collection searchDealer(Context context, String s) {
    Collection dlist = getDealerList(context);
    Collection ret = new ArrayList();
    s = s.toLowerCase(); // first search by postal code for (Dealer d : dlist) { if (d.postcode != null && d.postcode.toLowerCase().contains(s)) { ret.add(d); Log.d(TAG, "search found dealer:" + d.name); break; } } //get lat/lon if(!ret.isEmpty()){ Dealer d = ret.iterator().next(); ret.clear(); ret.add(fillLatLon(d,context)); } // only search by postcode /* * if (ret.isEmpty()) {// search by road for (Dealer d : dlist) { if * (d.road != null && d.road.toLowerCase().contains(s)) { ret.add(d); * Log.d("huyndai", "search found by road. dealer:" + d.name); break; } * } } if (ret.isE开发者_开发知识库mpty()) {// search by addres for (Dealer d : dlist) { * if (d.address != null && d.address.toLowerCase().contains(s)) { * ret.add(d); Log.d("huyndai", "search found by address. dealer:" + * d.name); break; } } } */ return ret; } private static Dealer fillLatLon(Dealer d,Context context){ Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    try {
     List addresses = geoCoder.getFromLocationName(d.postcode, 5);

     if (addresses.size() > 0) {
      Log.d(TAG, "found address: " +

       addresses.get(0).getLatitude() + " - " + addresses.get(0).getLongitude());
      d.lat = (int)(addresses.get(0).getLatitude() * 1E6);
      d.lon = (int)(addresses.get(0).getLongitude() * 1E6);

     }
    } catch (IOException e) {
     e.printStackTrace();
    }
    return d;
   }

   public static Location getCurrentLocation() {
    if (curentLocation != null) {
     return curentLocation;
    } else {
     Location loc = new Location("");
     loc.setLatitude(53.0);
     loc.setLongitude(-2.0);
     return loc;
    }

   }

   public static void triggerLocation(final Context context) { // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

     // Define a listener that responds to location updates
     LocationListener locationListener = new LocationListener() {
      public void onLocationChanged(Location location) {
       // Called when a new location is found by the network location
       // provider.
       curentLocation = location;
       Log.d(TAG, "current location  = " + location.getLatitude() + " - "

        +
        location.getLongitude()); //Toast.makeText(context, "current location = " + location.getLatitude() + " - " + location.getLongitude(), Toast.LENGTH_LONG).show(); }

       public void onStatusChanged(String provider, int status, Bundle

        extras) {}

       public void onProviderEnabled(String provider) {}

       public void onProviderDisabled(String provider) {}
      };
      Log.d(TAG, "getting current location"); // Register the listener

      with the Location Manager to receive location // updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); Location loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

      if (loc == null) {
       loc =

        locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      }

      if (loc != null) {
       Log.d(TAG, "Last known location  = " +

        loc.getLatitude() + " - " + loc.getLongitude());
       curentLocation = loc;
      }
     }

     public static Dealer findNearest(Context context) {
      Location currentLocation = getCurrentLocation();

      Collection < Dealer > dlist = getDealerList(context);
      Dealer

      foundDealer = null;
      float currentNearestDistance = 0;

      for (Dealer d: dlist) {

       Location dLoc = new Location("dealer location");
       dLoc.setLatitude(d.lat / 1E6);
       dLoc.setLongitude(d.lon / 1E6);
       float distance = dLoc.distanceTo(currentLocation);
       Log.d(TAG,

        "Dealer: " + d.name + " distance = " + distance);
       if (currentNearestDistance == 0 || currentNearestDistance > distance) { // set // init // value currentNearestDistance = distance; foundDealer = d; } } return fillLatLon(foundDealer,context); }

        public static void callTel(Context context, String tel) {
         try {
          Intent callIntent = new Intent(Intent.ACTION_CALL);
          callIntent.setData(Uri.parse("tel:" + tel));
          context.startActivity(callIntent);
         } catch (ActivityNotFoundException e) {
          Log.e(TAG, "Call failed", e);
         }
        }

        public static void sendEmail(String email, String first, String last, String title, String opt, Handler handle) {
         if (title.toLowerCase().equals("title")) {
          title = "";
         }
         try {
          String getURL = "https://clients.mobext.co.uk/hyundai/sendemail?email=" + URLEncoder.encode(email) + "&first_name=" + URLEncoder.encode(first) + "&last_name=" + URLEncoder.encode(last) + "&title=" + title + "&opt=" + opt + "&agent=android";
          HttpURLConnection http = null;
          Log.d(TAG, "request brochure: " + getURL);
          URL url = new URL(getURL);

          if (url.getProtocol().toLowerCase().equals("https")) {
           trustAllHosts();
           HttpsURLConnection https = (HttpsURLConnection)

           url.openConnection();
           https.setHostnameVerifier(DO_NOT_VERIFY);
           http = https;
          } else {
           http = (HttpURLConnection) url.openConnection();
          }
          BufferedReader rd = new BufferedReader(new InputStreamReader(http.getInputStream())); // read d response till d end String line = ""; while ((line = rd.readLine()) != null) {// process the line response Log.i(TAG, line); } Message m = new Message(); m.arg1 = 1; handle.sendMessage(m); } catch (Exception e) { e.printStackTrace(); Message m = new Message(); m.arg1 = -1; handle.sendMessage(m); }

         }

         // always verify the host - dont check for certificate final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } };

         /** * Trust every server - dont check for any certificate */
         private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return new java.security.cert.X509Certificate[] {};
          }

          public void checkClientTrusted(X509Certificate[] chain, String

           authType) throws CertificateException {}

          public void checkServerTrusted(X509Certificate[] chain, String

           authType) throws CertificateException {}
         }
        };

        // Install the all-trusting trust manager       try {           SSLContext sc =

        SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
       } catch (Exception e) {
        e.printStackTrace();
       }
      }
     }


Any help would be greatly appreciated.

0

精彩评论

暂无评论...
验证码 换一张
取 消