有时谷歌距离矩阵ZERO_RESULTS返回

时间:2016-12-15 02:55:33

标签: ios swift core-location latitude-longitude google-distancematrix-api

如果我设置默认 lat long ,那么my first question即可正常工作,现在我尝试获取位置当前位置并使用它。我也跟着这个Get User's Current Location / Coordinates但未能达到结果。

我不确定这里发生的事情是不行的尝试以多种方式进行

   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();
        }
每次json响应时都有

API

  

status =“ZERO_RESULTS”;

我的目标: 我不确定为什么代码不能正常工作我的主要目标是:获取用户当前位置和目的地来计算持续时间和公里。

2 个答案:

答案 0 :(得分:1)

详细

swift 3,xCode 8.2

获取当前位置的完整样本

  

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

添加

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Test</string>

模拟器设置

enter image description here

结果

enter image description here enter image description here

答案 1 :(得分:0)

当我设置目的地“50.087692,14.421150”且来源是“37.33019332,-122.02298792”

{
    "destination_addresses" =     (
        "50.087692,14.42115"
    );
    "origin_addresses" =     (
        "37.33019332,-122.02298792"
    );
    rows =     (
                {
            elements =             (
                                {
                    status = "ZERO_RESULTS";
                }
            );
        }
    );
    status = OK;
}

谷歌地图说:

抱歉,我们无法计算从来源目的地的路线 这就是为什么要回归

  

status =“ZERO_RESULTS”;

如果我设置目的地“37.421219,-122.084205”且来源是“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;
}