【问题标题】:Google Maps RouteBoxer in iOS AppiOS App 中的 Google Maps RouteBoxer
【发布时间】:2015-12-04 16:53:56
【问题描述】:

我想知道是否可以在使用 Google Maps API 的 iOS 应用中实现 RouteBoxer?如果没有,是否有另一种方法可以在路线上找到 POI?我对 HTML 不是很熟悉,但是有没有办法通过发出 HTTP 请求来访问 RouteBoxer?使用 RouteBoxer 需要网页和地图可见吗?我在后端使用 Parse.com,因此如果需要,我还可以使用 Javascript 在云中发出 HTTP 请求。

【问题讨论】:

  • 嗨雅各布,我也面临同样的问题。你有解决办法吗?
  • @KotiTummala 还没有,抱歉!! :(

标签: ios google-maps google-maps-api-3 parse-platform maps


【解决方案1】:

我现在找到了解决方案(我不知道这样做是否正确)。我正在做的是将 Routeboxer.JS 文件添加到项目中,并创建 HTML 文件以从返回框的 Routeboxer.js 文件中调用框函数。

这是 HTML 文件代码..

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps JavaScript API Search Along a Route Example</title>
        <script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>
        <script src="RouteBoxer.js" type="text/javascript"></script>
        <script type="text/javascript">

        var boxpolys = null;
        var directions = null;
        var routeBoxer = null;
        var distance = null; // km

        function initialize() {
          // Default the map view to the continental U.S.
          routeBoxer = new RouteBoxer();
          directionService = new google.maps.DirectionsService();
        }

        function route(source, destination, distance) {
          // Convert the distance to box around the route from miles to km
          //distance = parseFloat(document.getElementById("distance").value) * 1.609344;
          routeBoxer = new RouteBoxer();
          directionService = new google.maps.DirectionsService();
          //route("Hyderabad", "Vijayawada", "5");
          distance = parseFloat(distance) * 1.609344;
          var request = {
            origin: source,
            destination: destination,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
          }
          // Make the directions request
          //onload="route('Vijayawada','Hyderabad','5');
          var boxes;
          directionService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
              //directionsRenderer.setDirections(result);
              // Box around the overview path of the first route
              var path = result.routes[0].overview_path;
              var boxes = routeBoxer.box(path, distance);
//This object to get the boxes array to get the places from api call
                                 var result = JSON.stringify(boxes);
                                 console.log(result);
                                 var data = [];

                                 for (var i = 0; i < boxes.length; i++) {

                                 //This object to draw the boxes..
                                 var str = {"NE": [boxes[i].getNorthEast().lat(), boxes[i].getNorthEast().lng()], "SE": [boxes[i].getSouthWest().lat(), boxes[i].getNorthEast().lng()], "SW": [boxes[i].getSouthWest().lat(), boxes[i].getSouthWest().lng()], "NW": [boxes[i].getNorthEast().lat(), boxes[i].getSouthWest().lng()], "WW": [boxes[i].getNorthEast().lat(), boxes[i].getNorthEast().lng()]};
                                 data.push(str)
                                 }
                                 var latLng = JSON.stringify(data)
                                 console.logCoord(latLng);
                                 //return JSON.Stringify(boxes);
            } else {
              alert("Directions query failed: " + status);
                                 return "Direction query failed";
            }
          });
        }
        //As direction service.route method is Asynchronous call we can't return anything from this function so we added the console.log to get the data back to iOS
        console = new Object();
        console.log = function(log) {
            var iframe = document.createElement("IFRAME");
            iframe.setAttribute("src", "ios-log:#iOS#" + log);

            document.documentElement.appendChild(iframe);
            iframe.parentNode.removeChild(iframe);
            iframe = null;
        };
        console.debug = console.log;
        console.info = console.log;
        console.warn = console.log;
        console.error = console.log;

        console.logCoord = function(log) {
            var coordiframe = document.createElement("IFRAME");
            coordiframe.setAttribute("src", "ios-coor:#iOS#" + log);
            document.documentElement.appendChild(coordiframe);
            coordiframe.parentNode.removeChild(coordiframe);
            coordiframe = null;
        };
        console.debug = console.logCoord;
        console.info = console.logCoord;
        console.warn = console.logCoord;
        console.error = console.logCoord;
    </script>
    </head>
    <body>
    </body>
    </html>

然后将 UIWebView 对象添加到视图控制器。无需对用户可见..!在 viewDidLoad 方法中,使用本地 HTML 文件加载 URL。这里simple-3是HTML文件名。

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = NSBundle.mainBundle().URLForResource("simpletest-3", withExtension:"html")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

下面是从javascript调用路由方法的示例函数..!调用此函数之前必须完成 Web 视图的加载

@IBAction func onClick(sender: UIButton!) {
        let function = String(format: "route('%@', '%@', '%@')", "Hyderabad", "Mysore", "5")
        //let function = String(format: "route('Vijayawada','Hyderabad','5')")
        let result = webView.stringByEvaluatingJavaScriptFromString(function)
        print("result is : \(result)")
    }

在 webview 的 Delegate 方法中我们可以得到结果(Boxes 数组,以及在 Map 上绘制 Boxes 的坐标)。

extension MapViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        print("web view did finsih loading")
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let urlString = request.URL?.absoluteString.stringByRemovingPercentEncoding {
            if urlString.hasPrefix("ios-log:") {
                let logString = urlString.componentsSeparatedByString(":#iOS#")[1]
                self.getPlacesForJsonData(logString)
                return false
            }
            if urlString.hasPrefix("ios-coor:") {
                let logString = urlString.componentsSeparatedByString(":#iOS#")[1]
                //print("logString is \(logString)")
                let data: NSData = logString.dataUsingEncoding(NSUTF8StringEncoding)!
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves)

                    //print("coordString is \(json)")
                    if let json = json as? NSArray {
                       self.drawBoxes(json)
                    }

                } catch {
                    print("JSON conversion error")
                }
                return false
            }
        }
        return true
    }
}

最后一件事是沿路线在地图上绘制方框..!

func drawBoxes(boxes: NSArray) {
        if boxes.count > 0 {
            for dict in boxes {
                let path = GMSMutablePath()
                path.addCoordinate(CLLocationCoordinate2DMake((dict["NE"] as! NSArray)[0].doubleValue, (dict["NE"] as! NSArray)[1].doubleValue))
                path.addCoordinate(CLLocationCoordinate2DMake((dict["SE"] as! NSArray)[0].doubleValue, (dict["SE"] as! NSArray)[1].doubleValue))
                path.addCoordinate(CLLocationCoordinate2DMake((dict["SW"] as! NSArray)[0].doubleValue, (dict["SW"] as! NSArray)[1].doubleValue))
                path.addCoordinate(CLLocationCoordinate2DMake((dict["NW"] as! NSArray)[0].doubleValue, (dict["NW"] as! NSArray)[1].doubleValue))

                // Create the polygon, and assign it to the map.
                let polygon = GMSPolygon(path: path)
                polygon.fillColor = UIColor(red:1.0, green:0, blue:0, alpha:0.25);
                //polygon.strokeColor = UIColor.blackColor()
                polygon.strokeWidth = 0
                polygon.map = mapView
            }
        }
    }

希望对您有所帮助,如果您对此有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多