如何从当前位置绘制路径到从Mysql数据库检索到的位置

时间:2017-03-22 06:32:38

标签: android mysql google-maps

我是android编程的新手。我已经从数据库和当前位置检索了LatLng。问题是我不知道如何从两个标记画出路径。谢谢:)这是我的地图活动。

public class ModelMap extends AppCompatActivity  implements OnMapReadyCallback, View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

Button btnGo;
AutoCompleteTextView etSearch;

LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;

LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_model_map);

    btnGo = (Button) findViewById(R.id.btnGo);
    etSearch = (AutoCompleteTextView) findViewById(R.id.etSearch);
    btnGo.setOnClickListener(this);


    getMap();
}

@Override
public void onClick(View view) {

            ArrayList<HashMap<String, String>> location = null;
            String url = "http://enyatravel.com/maps/mapsdata/mapsModel.php";

            try {
                JSONArray data = new JSONArray(getHttpGet(url));
                location = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> map;

                for (int i = 0; i < data.length(); i++) {
                    JSONObject c = data.getJSONObject(i);

                    map = new HashMap<String, String>();
                    map.put("location_id", c.getString("location_id"));
                    map.put("latitude", c.getString("latitude"));
                    map.put("longitude", c.getString("longitude"));
                    map.put("name", c.getString("name"));
                    location.add(map);


                }
            } catch (JSONException e) {

                e.printStackTrace();
            }
            mGoogleMap.getUiSettings().setMapToolbarEnabled(false);
            mGoogleMap.getUiSettings().setCompassEnabled(false);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);

            //zoom

            Double latitude = Double.parseDouble(location.get(0).get("latitude").toString());
            Double longitude = Double.parseDouble(location.get(0).get("longitude").toString());
            LatLng coordinate = new LatLng(latitude, longitude);
            mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

            //marker

            for (int i = 0; i < location.size(); i++) {
                latitude = Double.parseDouble(location.get(i).get("latitude").toString());
                longitude = Double.parseDouble(location.get(i).get("longitude").toString());
                String name = location.get(i).get("name").toString();
                MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(name);
                mGoogleMap.addMarker(marker);

            }




}


public void getMap() {
    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googlemaps);
    mFragment.getMapAsync(this);
}

public static String getHttpGet(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpget);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download result..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}

@Override
public void onMapReady(GoogleMap googleMap) {

    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    mGoogleMap = googleMap;
    mGoogleMap.setMyLocationEnabled(true);

    buildGoogleApiClient();

    mGoogleApiClient.connect();


}

protected synchronized void buildGoogleApiClient() {
    Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        //place marker at current position
        //mGoogleMap.clear();
        latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icongps));
        currLocationMarker = mGoogleMap.addMarker(markerOptions);
    }

    mLocationRequest = new LocationRequest();
    // mLocationRequest.setInterval(5000); //5 seconds
    // mLocationRequest.setFastestInterval(3000); //3 seconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
}

@Override
public void onLocationChanged(Location location) {

    //place marker at current position
    //mGoogleMap.clear();
    if (currLocationMarker != null) {
        currLocationMarker.remove();
    }
    latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icontao));
    currLocationMarker = mGoogleMap.addMarker(markerOptions);

    //Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();

    //zoom to current position:
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));

    //If you only need one location, unregister the listener
    //LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

}

}

PHP:      

$strSQL ="SELECT * FROM `loc_info` WHERE name= 'Saverde Coffee Shop'";

$objQuery = mysqli_query($objConnect, $strSQL);
// or die (mysqli_error());
$arrRows = array();
$arryItem = array();


while($arr = mysqli_fetch_array($objQuery)){
$arryItem["location_id"] = $arr["location_id"];
$arryItem["latitude"] = $arr["latitude"];
$arryItem["longitude"] = $arr["longitude"];
$arryItem["name"] = $arr["name"];
$arrRows[]= $arryItem;

}


echo json_encode($arrRows);


?>

2 个答案:

答案 0 :(得分:1)

如果您想要绘制路径的两个点(标记),则必须使用latlong绘制PolliLines。下面的代码将在地图上绘制您的路径。

@IBOutlet weak var mapView: MKMapView!

//my location

let manager = CLLocationManager()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations[0]

    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    mapView.setRegion(region, animated: true)

    print(location.altitude)
    print(location.speed)

    self.mapView.showsUserLocation = true

}

override func viewDidLoad() {
    super.viewDidLoad()

    //my location
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()


    let distanceSpan:CLLocationDegrees = 250

    //KT1 Annotation
    let KT1Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.310491, 114.227998)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(KT1Location, distanceSpan, distanceSpan),animated: true)
    let KT1CSClassPin = KT1Annotation(title: "觀塘工業中心第一期", subtitle: "觀塘道 472-484號", coordinate: KT1Location)
    mapView.addAnnotation( KT1CSClassPin )

    //KT2 Annotation
    let KT2Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.310724, 114.227626)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(KT2Location, distanceSpan, distanceSpan),animated: true)
    let KT2CSClassPin = KT2Annotation(title: "觀塘工業中心第二期", subtitle: "觀塘道 460-470號", coordinate: KT2Location)
    mapView.addAnnotation( KT2CSClassPin )

    //KT3 Annotation
    let KT3Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.310957, 114.227255)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(KT3Location, distanceSpan, distanceSpan),animated: true)
    let KT3CSClassPin = KT3Annotation(title: "觀塘工業中心第三期", subtitle: "觀塘道 448-458號", coordinate: KT3Location)
    mapView.addAnnotation( KT3CSClassPin )

    //KT4 Annotation
    let KT4Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.311364, 114.226883)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(KT4Location, distanceSpan, distanceSpan),animated: true)
    let KT4CSClassPin = KT4Annotation(title: "觀塘工業中心第四期", subtitle: "觀塘道 436-446號", coordinate: KT4Location)
    mapView.addAnnotation( KT4CSClassPin )

    //CP1 Annotation
    let CP1Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.310459, 114.22516470000005)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(CP1Location, distanceSpan, distanceSpan),animated: true)
    let CP1CSClassPin = CP1Annotation(title: "駱駝漆大廈第1座", subtitle: "開源道 62號", coordinate: CP1Location)
    mapView.addAnnotation( CP1CSClassPin )

    //CP3 Annotation
    let CP3Location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(22.310125, 114.225072)
    mapView.setRegion(MKCoordinateRegionMakeWithDistance(CP3Location, distanceSpan, distanceSpan),animated: true)
    let CP3CSClassPin = CP3Annotation(title: "駱駝漆大廈第3座", subtitle: "開源道 60號", coordinate: CP3Location)
    mapView.addAnnotation( CP3CSClassPin )

}

只需点击链接即可。 Answer : Draw path between two points using Google Maps Android API v2

答案 1 :(得分:0)

您可以使用Polyline。我已经分享了链接,第一个将为您提供直接的简单实现。另一个是提高你的理解。

Polyline Implementation
Maps v2, Using Polyline