问题
It is my first question about that is working if I set default lat and long and now I try to get location current location and use that. Also I following this one Get User's Current Location / Coordinates but failed to reach result.
I am not sure what is going on here it is not working try to do it several way
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//print(locations)
//get the actual location from the device and first one each move
let userClLocation : CLLocation = locations[0]
let latitude = userClLocation.coordinate.latitude
let longitude = userClLocation.coordinate.longitude
durationDestance(origin: "\(latitude),\(longitude)", destination: destination, mode:"auto")
}
func durationDestance(origin: String, destination: String, mode:String) {
var urlString : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(origin)&destinations=\(destination)&mode=\(mode)&key=AIzaSyAVOt9LLagNGSOI8O0ri1Sbahcl_q5AFYc";
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
let session = URLSession.shared
let url = URL(string:urlString)!
session.dataTask(with: url) { (data: Data?, response: URLResponse?, erorr: Error?) -> Void in
print("url: \(urlString)")
if let responseData = data {
do{
let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments);
print(json);
}
catch{
print("do not serialization :)");
}
}
}.resume();
}
API every time json response
status = "ZERO_RESULTS";
My Goal : I am not sure why code not working my main goal is: get user current location and destination to calculate duration time and km.
回答1:
Details
swift 3, xCode 8.2
Full sample to get current location
ViewController.swift
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
mapView.showsUserLocation = true
}
private func updateCurrentLocation() {
locationManager.startUpdatingLocation()
}
@IBAction func showCurrentLocation(_ sender: UIBarButtonItem) {
updateCurrentLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.2,0.2)
let region = MKCoordinateRegion(center: coordinations, span: span)
mapView.setRegion(region, animated: true)
print("Coordinate \(userLocation.coordinate)")
}
}
Mains.storyboard
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="u20-DK-FBK">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_25296691" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<mapView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" mapType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="5RZ-FN-eIO">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
</mapView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="5RZ-FN-eIO" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="BDg-DH-xgo"/>
<constraint firstAttribute="trailing" secondItem="5RZ-FN-eIO" secondAttribute="trailing" id="Bhl-4P-9cd"/>
<constraint firstItem="5RZ-FN-eIO" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="W2W-nx-2X6"/>
<constraint firstItem="5RZ-FN-eIO" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="top" id="fuU-IJ-q2W"/>
</constraints>
</view>
<navigationItem key="navigationItem" id="qbN-90-njV">
<barButtonItem key="rightBarButtonItem" title="Location" id="hoa-eP-AC4">
<connections>
<action selector="showCurrentLocation:" destination="BYZ-38-t0r" id="Wh7-el-edQ"/>
</connections>
</barButtonItem>
</navigationItem>
<connections>
<outlet property="mapView" destination="5RZ-FN-eIO" id="mL4-gS-1Qz"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="972" y="37.331334332833585"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="rry-ls-hJW">
<objects>
<navigationController automaticallyAdjustsScrollViewInsets="NO" id="u20-DK-FBK" sceneMemberID="viewController">
<toolbarItems/>
<navigationBar key="navigationBar" contentMode="scaleToFill" id="bcA-NR-zma">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<nil name="viewControllers"/>
<connections>
<segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="xyN-dx-lCn"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="tlB-hp-Doq" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="32.799999999999997" y="37.331334332833585"/>
</scene>
</scenes>
</document>
Info.plist
add
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Test</string>
Simulator settings
Result
回答2:
when i setting destination is "50.087692, 14.421150" and origin is "37.33019332,-122.02298792"
{
"destination_addresses" = (
"50.087692,14.42115"
);
"origin_addresses" = (
"37.33019332,-122.02298792"
);
rows = (
{
elements = (
{
status = "ZERO_RESULTS";
}
);
}
);
status = OK;
}
Google map saying :
Sorry, we could not calculate directions from origin to destination that's why return
status = "ZERO_RESULTS";
if I setting destination is "37.421219, -122.084205" and origin is "37.33055645,-122.02910148"
{
"destination_addresses" = (
"918 Charleston Rd, Mountain View, CA 94043, USA"
);
"origin_addresses" = (
"20400 Mariani Ave, Cupertino, CA 95014, USA"
);
rows = (
{
elements = (
{
distance = {
text = "15.0 km";
value = 15041;
};
duration = {
text = "14 mins";
value = 851;
};
status = OK;
}
);
}
);
status = OK;
}
来源:https://stackoverflow.com/questions/41155676/sometime-google-distance-matrix-zero-results-returned