Navigation SDK זמין כרגע רק ללקוחות נבחרים. למידע נוסף, אפשר לפנות למחלקת המכירות.
עיצוב חדש של מפות יהיה זמין בקרוב בפלטפורמה של מפות Google. העדכון הזה בסגנון המפה כולל לוח צבעים חדש שמוגדר כברירת מחדל ושיפורים בחוויית השימוש במפות ובנוחות השימוש. כל סגנונות המפה יעודכנו באופן אוטומטי במרץ 2025. אפשר לקרוא מידע נוסף על זמינות ועל האפשרות להצטרף בשלב מוקדם יותר במאמר בנושא סגנון מפה חדש לפלטפורמה של מפות Google.
כדי להציג או להסתיר את קוד ה-SWIFT ולקבל את פרטי המסלול.
/**Copyright2017GoogleInc.Allrightsreserved.**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"AS IS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/importGoogleNavigationimportUIKitclassViewController:UIViewController{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptedinguardtermsAcceptedelse{//Handlethecasewhentheuserrejectsthetermsandconditions.return}//Enablenavigationaftertheuseracceptstheterms.self.mapView.isNavigationEnabled=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()}self.view=mapViewmakeButtons()}//Createarouteandstartguidance.funcstartNav(){vardestinations=[GMSNavigationWaypoint]()destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJnUYTpNASkFQR_gSty5kyoUk",title:"PCC Natural Market")!)destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJJ326ROcSkFQRBfUzOL2DSbo",title:"Marina Park")!)mapView.navigator?.setDestinations(destinations){routeStatusinguardrouteStatus==.OKelse{print("Handle route statuses that are not OK.")return}self.mapView.navigator?.isGuidanceActive=trueself.mapView.cameraMode=.followingself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()}mapView.roadSnappedLocationProvider?.startUpdatingLocation()}funcgetTimeToNextDestination(){ifletnavigator=mapView.navigator{lettime=navigator.timeToNextDestinationletminutes=floor(time/60)letseconds=round(time-minutes*60)print("Time to next destination: \(minutes):\(seconds)")}}funcgetDistanceToNextDestination(){ifletnavigator=mapView.navigator{letdistance=navigator.distanceToNextDestinationletmiles=distance*0.00062137print("Distance to next destination: \(miles) miles.")}}funcgetCurrentRouteLeg(){ifletnavigator=mapView.navigator{letcurrentLeg=navigator.currentRouteLegletnextDestination=currentLeg?.destinationWaypoint?.title??"Not Available"letlat=currentLeg?.destinationCoordinate.latitude.description??"Not Available"letlng=currentLeg?.destinationCoordinate.longitude.description??"Not Available"print("Destination: \(nextDestination) at (\(lat),\(lng)")}}funcgetTraveledPath(){ifletnavigator=mapView.navigator{letlatestPath=navigator.traveledPathiflatestPath.count() > 0{letbegin:CLLocationCoordinate2D=latestPath.coordinate(at:0)letcurrent:CLLocationCoordinate2D=latestPath.coordinate(at:latestPath.count()-1)print("Path from (\(begin.latitude),\(begin.longitude)) to (\(current.latitude),\(current.longitude))")}}}//Addsomebuttonstotheview.funcmakeButtons(){//Startnavigation.letnavButton=UIButton(frame:CGRect(x:5,y:150,width:200,height:35))navButton.backgroundColor=.bluenavButton.alpha=0.5navButton.setTitle("Start navigation",for:.normal)navButton.addTarget(self,action:#selector(startNav), for: .touchUpInside)self.mapView.addSubview(navButton)//Getthetimetothenextdestination.lettimeButton=UIButton(frame:CGRect(x:5,y:190,width:200,height:35))timeButton.backgroundColor=.bluetimeButton.alpha=0.5timeButton.setTitle("Time to next destination",for:.normal)timeButton.addTarget(self,action:#selector(getTimeToNextDestination), for: .touchUpInside)self.mapView.addSubview(timeButton)//Getthedistancetothenextdestination.letdistanceButton=UIButton(frame:CGRect(x:5,y:230,width:200,height:35))distanceButton.backgroundColor=.bluedistanceButton.alpha=0.5distanceButton.setTitle("Distance to next destination",for:.normal)distanceButton.addTarget(self,action:#selector(getDistanceToNextDestination), for: .touchUpInside)self.mapView.addSubview(distanceButton)//Getthecurrentrouteleg.letrouteButton=UIButton(frame:CGRect(x:5,y:270,width:200,height:35))routeButton.backgroundColor=.bluerouteButton.alpha=0.5routeButton.setTitle("Get current route leg",for:.normal)routeButton.addTarget(self,action:#selector(getCurrentRouteLeg), for: .touchUpInside)self.mapView.addSubview(routeButton)//Getthemostrecentlytraveledpath.letpathButton=UIButton(frame:CGRect(x:5,y:310,width:200,height:35))pathButton.backgroundColor=.bluepathButton.alpha=0.5pathButton.setTitle("Get traveled path",for:.normal)pathButton.addTarget(self,action:#selector(getTraveledPath), for: .touchUpInside)self.mapView.addSubview(pathButton)}}
הצגה/הסתרה של קוד Objective-C כדי לקבל את פרטי המסלול.
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */#import "ViewController.h"@importGoogleNavigation;@interfaceViewController()@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Show the terms and conditions.NSString*companyName=@"Ride Sharing Co.";[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithCompanyName:companyNamecallback:^(BOOLtermsAccepted){if(termsAccepted){// Enable navigation if the user accepts the terms._mapView.navigationEnabled=YES;// Request authorization to use location services.[_locationManagerrequestAlwaysAuthorization];}else{// Handle the case when the user rejects the terms and conditions.}}];self.view=_mapView;[selfmakeButtons];}// Create a route and start guidance.-(void)startNav{NSArray<GMSNavigationWaypoint*>*destinations=@[[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"title:@"PCC Natural Market"],[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"title:@"Marina Park"]];[_mapView.navigatorsetDestinations:destinationscallback:^(GMSRouteStatusrouteStatus){_mapView.navigator.guidanceActive=YES;_mapView.cameraMode=GMSNavigationCameraModeFollowing;[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];}];[_mapView.roadSnappedLocationProviderstartUpdatingLocation];}-(void)getTimeToNextDestination{NSTimeIntervaltime=_mapView.navigator.timeToNextDestination;intminutes=floor(time/60);intseconds=round(time-minutes*60);NSLog(@"%@",[NSStringstringWithFormat:@"Time to next destination: %i:%i.",minutes,seconds]);}-(void)getDistanceToNextDestination{CLLocationDistancedistance=_mapView.navigator.distanceToNextDestination;doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);}-(void)getCurrentRouteLeg{GMSRouteLeg*currentSegment=_mapView.navigator.currentRouteLeg;NSString*nextDestination=currentSegment.destinationWaypoint.title;CLLocationDegreeslat=currentSegment.destinationCoordinate.latitude;CLLocationDegreeslng=currentSegment.destinationCoordinate.longitude;NSLog(@"%@",[NSStringstringWithFormat:@"%@, %f/%f",nextDestination,lat,lng]);}-(void)getTraveledPath{GMSPath*latestPath=_mapView.navigator.traveledPath;if(latestPath.count > 0){CLLocationCoordinate2Dbegin=[latestPathcoordinateAtIndex:0];CLLocationCoordinate2Dcurrent=[latestPathcoordinateAtIndex:latestPath.count-1];NSLog(@"Path from %f/%f to %f/%f",begin.latitude,begin.longitude,current.latitude,current.longitude);}}#pragma mark - Buttons and things// Add some buttons to the view.-(void)makeButtons{// Start navigation.UIButton*navButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Start navigation"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];[navButtonsetAlpha:0.5];navButton.frame=CGRectMake(5.0,150.0,200.0,35.0);[_mapViewaddSubview:navButton];// Get the time to the next destination.UIButton*timeButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[timeButtonaddTarget:selfaction:@selector(getTimeToNextDestination)forControlEvents:UIControlEventTouchUpInside];[timeButtonsetTitle:@"Time to next destination"forState:UIControlStateNormal];[timeButtonsetBackgroundColor:[UIColorblueColor]];[timeButtonsetAlpha:0.5];timeButton.frame=CGRectMake(5.0,190.0,200.0,35.0);[_mapViewaddSubview:timeButton];// Get the distance to the next destination.UIButton*distanceButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[distanceButtonaddTarget:selfaction:@selector(getDistanceToNextDestination)forControlEvents:UIControlEventTouchUpInside];[distanceButtonsetTitle:@"Distance to next destination"forState:UIControlStateNormal];[distanceButtonsetBackgroundColor:[UIColorblueColor]];[distanceButtonsetAlpha:0.5];distanceButton.frame=CGRectMake(5.0,230.0,200.0,35.0);[_mapViewaddSubview:distanceButton];// Get the current route leg.UIButton*routeButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[routeButtonaddTarget:selfaction:@selector(getCurrentRouteLeg)forControlEvents:UIControlEventTouchUpInside];[routeButtonsetTitle:@"Get current route leg"forState:UIControlStateNormal];[routeButtonsetBackgroundColor:[UIColorblueColor]];[routeButtonsetAlpha:0.5];routeButton.frame=CGRectMake(5.0,270.0,200.0,35.0);[_mapViewaddSubview:routeButton];// Get the most recently traveled path.UIButton*pathButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[pathButtonaddTarget:selfaction:@selector(getTraveledPath)forControlEvents:UIControlEventTouchUpInside];[pathButtonsetTitle:@"Get current route leg"forState:UIControlStateNormal];[pathButtonsetBackgroundColor:[UIColorblueColor]];[pathButtonsetAlpha:0.5];pathButton.frame=CGRectMake(5.0,310.0,200.0,35.0);[_mapViewaddSubview:pathButton];}@end
הצגת משך הנסיעה ליעד הבא
כדי לקבל את משך הנסיעה ליעד הבא, מקישים על timeToNextDestination().
הפונקציה מחזירה ערך NSTimeInterval. בדוגמה הבאה מוצגת רישום ביומן של הזמן ליעד הבא:
Swift
ifletnavigator=mapView.navigator{lettime=navigator.timeToNextDestinationletminutes=floor(time/60)letseconds=round(time-minutes*60)NSLog("Time to next destination: %.0f:%.0f",minutes,seconds)}
Objective-C
NSTimeIntervaltime=_mapView.navigator.timeToNextDestination;intminutes=floor(time/60);intseconds=round(time-minutes*60);NSLog(@"%@",[NSStringstringWithFormat:@"Time to next destination: %i:%i.",minutes,seconds]);
הצגת המרחק ליעד הבא
כדי לקבל את המרחק ליעד הבא, קוראים את הפקודה distanceToNextDestination().
הפונקציה מחזירה ערך CLLocationDistance. היחידות מצוינות במטרים.
Swift
ifletnavigator=mapView.navigator{letdistance=navigator.distanceToNextDestinationletmiles=distance*0.00062137NSLog("Distance to next destination: %.2f miles.",miles)}
Objective-C
CLLocationDistancedistance=_mapView.navigator.distanceToNextDestination;doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);
קבלת מידע על מצב התנועה ליעד הבא
כדי לקבל ערך שמציין את זרימת התנועה ליעד הבא, צריך להפעיל את הפונקציה delayCategoryToNextDestination.
הפרמטר הזה מחזיר את הערך GMSNavigationDelayCategory. בדוגמה הבאה מוצגת הערכת התוצאה ורישום ביומן של הודעת תנועה:
Swift
ifletnavigator=mapView.navigator{// insert sample for evaluating traffic valueletdelay=navigator.delayCategoryToNextDestinationlettraffic="unavailable"switchdelay{case.noData:traffic="unavailable"case.heavy:traffic="heavy"case.medium:traffic="moderate"case.light:traffic="light"default:traffic="unavailable"}print("Traffic is \(traffic).")}
Objective-C
GMSNavigationDelayCategorydelay=mapView.navigator.delayCategoryToNextDestination;NSString*traffic=@"";switch(delayCategory){caseGMSNavigationDelayCategoryNoData:traffic=@"No Data";break;caseGMSNavigationDelayCategoryHeavy:traffic=@"Heavy";break;caseGMSNavigationDelayCategoryMedium:traffic=@"Medium";break;caseGMSNavigationDelayCategoryLight:traffic=@"Light";break;default:NSLog(@"Invalid delay category: %zd",delayCategory);}NSLog(@"%@",[NSStringstringWithFormat:@"Traffic is %@.",traffic]);
הצגת מידע על המסלול הנוכחי
כדי לקבל מידע על מקטע המסלול הנוכחי, מקישים על currentRouteLeg.
הפונקציה מחזירה מופע של GMSRouteLeg, שממנו אפשר לקבל:
היעד של הקטע.
הקואורדינטה האחרונה בקטע.
הנתיב שמכיל את הקואורדינטות שמרכיבות את מקטע המסלול.
בדוגמה הבאה מוצג רישום ביומן של השם ושל קואורדינטות ה-lat/lng של הקטע הבא במסלול:
כדי לקבל את המסלול האחרון שנסעתם בו, צריך להפעיל את הפקודה traveledPath.
הפונקציה מחזירה מופע של GMSPath שעבר פשטון כדי להסיר נקודות מיותרות (לדוגמה, הפיכת נקודות רצופות על קו ישר לקטעי קו יחידים). הנתיב הזה ריק עד שההנחיה מתחילה. בדוגמה הבאה מוצגת הצגת הנתיב שעברתם בו לאחרונה:
Swift
ifletnavigator=mapView.navigator{letlatestPath=navigator.traveledPathiflatestPath.count() > 0{letbegin:CLLocationCoordinate2D=latestPath.coordinate(at:0)letcurrent:CLLocationCoordinate2D=latestPath.coordinate(at:latestPath.count()-1)print("Path from (\(begin.latitude),\(begin.longitude)) to (\(current.latitude),\(current.longitude))")}}
Objective-C
GMSPath*latestPath=mapView.navigator.traveledPath;if(latestPath.count > 0){CLLocationCoordinate2Dbegin=[latestPathcoordinateAtIndex:0];CLLocationCoordinate2Dcurrent=[latestPathcoordinateAtIndex:latestPath.count-1];NSLog(@"Path from %f/%f to %f/%f",begin.latitude,begin.longitude,current.latitude,current.longitude);}