ios - iOS 应用中的谷歌地图 RouteBoxer

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

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

最佳答案

我现在找到了解决方案(我不知道这是正确的方法)。我正在做的是将 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 对象添加到 View Controller 。不需要对用户可见..!在 viewDidLoad 方法中加载带有本地 HTML 文件的 URL。这里 simplest-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 View 的加载

@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
    }
}

最后一件事是沿着路线在 map 上画框..!

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
            }
        }
    }

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

关于ios - iOS 应用中的谷歌地图 RouteBoxer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467378/

相关文章:

ios - enumerateObjectsUsingBlock 中的 weakSelf?

ios - 如何在不安装客户端应用程序的情况下设置 Fabric/Crashlytics

google-maps - 谷歌地图无法加载。卡在 authenticationService.authenticate

javascript - MarkerClusterer 不聚类标记

google-maps-api-3 - 如何更改 Google Maps API V3 中的图标颜色?

ios - iOS 空引荐来源网址的谷歌位置

ios - 刷新 UITableView 中的分页数据

javascript - Fusion Tables 层中超过最大 URL 长度的请求

javascript - 在谷歌地图API中向多个标记添加标签

javascript - jquery不同的标记颜色