خدمات مسیرها

بررسی اجمالی

با استفاده از شی DirectionsService می توانید جهت ها را (با استفاده از روش های مختلف حمل و نقل) محاسبه کنید. این شی با سرویس مسیرهای API Google Maps ارتباط برقرار می کند که درخواست های جهت را دریافت می کند و یک مسیر کارآمد را برمی گرداند. زمان سفر عامل اولیه ای است که بهینه می شود، اما عوامل دیگری مانند مسافت، تعداد دور و بسیاری موارد دیگر ممکن است در نظر گرفته شوند. می‌توانید این نتایج دستورالعمل‌ها را خودتان مدیریت کنید یا از شی DirectionsRenderer برای ارائه این نتایج استفاده کنید.

هنگام تعیین مبدا یا مقصد در یک درخواست جهت، می توانید یک رشته پرس و جو (به عنوان مثال، "Chicago, IL" یا "Darwin, NSW, Australia")، یک مقدار LatLng یا یک شی Place را مشخص کنید.

سرویس Directions می تواند جهت های چند بخشی را با استفاده از یک سری از ایستگاه های بین راه بازگرداند. مسیرها به صورت چند خطی که مسیر را بر روی نقشه ترسیم می‌کند، یا به‌عنوان مجموعه‌ای از توضیحات متنی در یک عنصر <div> نمایش داده می‌شوند (مثلاً «به سمت راست روی سطح شیبدار پل ویلیامزبورگ بپیچید»).

شروع شدن

قبل از استفاده از سرویس Directions در Maps JavaScript API، ابتدا مطمئن شوید که Directions API در Google Cloud Console، در همان پروژه ای که برای Maps JavaScript API تنظیم کرده اید، فعال است.

برای مشاهده لیست API های فعال:

  1. به Google Cloud Console بروید.
  2. روی دکمه Select a project کلیک کنید، سپس همان پروژه ای را که برای Maps JavaScript API تنظیم کرده اید انتخاب کنید و روی Open کلیک کنید.
  3. از لیست APIها در داشبورد ، به دنبال Directions API بگردید.
  4. اگر API را در لیست مشاهده کردید، همه چیز آماده است. اگر API در لیست نیست ، آن را فعال کنید:
    1. در بالای صفحه، ENABLE API را انتخاب کنید تا تب Library نمایش داده شود. یا از منوی سمت چپ، کتابخانه را انتخاب کنید.
    2. Directions API را جستجو کنید، سپس آن را از لیست نتایج انتخاب کنید.
    3. ENABLE را انتخاب کنید. وقتی فرآیند به پایان رسید، Directions API در لیست APIها در داشبورد ظاهر می‌شود.

قیمت گذاری و سیاست ها

قیمت گذاری

از 16 ژوئیه 2018، یک طرح جدید قیمت‌گذاری پرداختی برای Maps، Routes و Places اجرا شد. برای اطلاعات بیشتر در مورد قیمت‌گذاری و محدودیت‌های استفاده جدید برای استفاده از سرویس JavaScript Directions، به Usage and Billing for Directions API مراجعه کنید.

سیاست های

استفاده از سرویس Directions باید مطابق با خط مشی های توضیح داده شده برای Directions API باشد.

درخواست مسیرها

دسترسی به سرویس Directions ناهمزمان است، زیرا Google Maps API باید با یک سرور خارجی تماس بگیرد. به همین دلیل، باید پس از تکمیل درخواست، یک متد برگشتی را ارسال کنید تا اجرا شود. این روش برگشتی باید نتیجه(های) را پردازش کند. توجه داشته باشید که سرویس Directions ممکن است بیش از یک برنامه سفر ممکن را به عنوان آرایه ای از routes[] .

برای استفاده از دستورالعمل‌ها در Maps JavaScript API، یک شی از نوع DirectionsService ایجاد کنید و DirectionsService.route() را فراخوانی کنید تا یک درخواست به سرویس Directions آغاز کند، و به آن یک شی DirectionsRequest ارسال کنید که حاوی عبارات ورودی و یک روش بازگشت به تماس است تا پس از دریافت آن اجرا شود. پاسخ.

شیء DirectionsRequest حاوی فیلدهای زیر است:

{
  origin: LatLng | String | google.maps.Place,
  destination: LatLng | String | google.maps.Place,
  travelMode: TravelMode,
  transitOptions: TransitOptions,
  drivingOptions: DrivingOptions,
  unitSystem: UnitSystem,
  waypoints[]: DirectionsWaypoint,
  optimizeWaypoints: Boolean,
  provideRouteAlternatives: Boolean,
  avoidFerries: Boolean,
  avoidHighways: Boolean,
  avoidTolls: Boolean,
  region: String
}

این فیلدها در زیر توضیح داده شده است:

  • origin ( الزامی ) محل شروع را مشخص می کند که از آن جهت محاسبه می شود. این مقدار ممکن است به عنوان یک String (به عنوان مثال، "Chicago, IL")، به عنوان یک مقدار LatLng یا به عنوان یک شی Place مشخص شود. اگر از یک شیء Place استفاده می کنید، می توانید شناسه مکان ، رشته پرس و جو یا مکان LatLng را مشخص کنید. می‌توانید شناسه‌های مکان را از سرویس‌های Geocoding، Place Search و Place Autocomplete در Maps JavaScript API بازیابی کنید. برای مثال استفاده از شناسه‌های مکان از تکمیل خودکار مکان، تکمیل خودکار مکان و مسیرها را ببینید.
  • destination ( مورد نیاز ) مکان پایانی را مشخص می کند که جهت ها را به آن محاسبه می کند. گزینه ها مانند فیلد origin که در بالا توضیح داده شد است.
  • travelMode ( مورد نیاز ) مشخص می کند که هنگام محاسبه مسیرها از چه نوع حمل و نقل استفاده شود. مقادیر معتبر در حالت های سفر در زیر مشخص شده است.
  • transitOptions ( اختیاری ) مقادیری را مشخص می کند که فقط برای درخواست هایی که travelMode TRANSIT است اعمال می شود . مقادیر معتبر در گزینه های حمل و نقل در زیر توضیح داده شده است.
  • drivingOptions ( اختیاری ) مقادیری را مشخص می کند که فقط برای درخواست هایی اعمال می شود که در آن travelMode DRIVING است. مقادیر معتبر در گزینه های رانندگی در زیر توضیح داده شده است.
  • unitSystem ( اختیاری ) مشخص می کند که از چه سیستم واحدی هنگام نمایش نتایج استفاده شود. مقادیر معتبر در سیستم های واحد در زیر مشخص شده است.

  • waypoints[] ( اختیاری ) آرایه ای از DirectionsWaypoint s را مشخص می کند. نقاط راه یک مسیر را با مسیریابی آن در مکان(های) مشخص شده تغییر می دهند. یک نقطه بین به عنوان یک شی به معنای واقعی کلمه با فیلدهای زیر مشخص می شود:

    • location مکان نقطه بین را مشخص می کند، به عنوان LatLng ، به عنوان یک شی Place یا به عنوان String که جغرافیایی کدگذاری می شود.
    • stopover یک بولی است که نشان می دهد که ایستگاه بین راه یک توقف در مسیر است که باعث تقسیم مسیر به دو مسیر می شود.

    (برای اطلاعات بیشتر در مورد نقاط بین راه، به استفاده از Waypoints در مسیرها در زیر مراجعه کنید.)

  • optimizeWaypoints ( اختیاری ) مشخص می کند که مسیری که از waypoints ارائه شده استفاده می کند، ممکن است با مرتب کردن مجدد نقاط بین راهی به ترتیب کارآمدتر بهینه شود. اگر true ، سرویس Directions waypoints ترتیب مجدد شده را در یک قسمت waypoint_order برمی گرداند. (برای اطلاعات بیشتر، استفاده از Waypoints در مسیرها را در زیر ببینید.)
  • provideRouteAlternatives ( اختیاری ) وقتی روی true تنظیم شود مشخص می کند که سرویس Directions ممکن است بیش از یک مسیر جایگزین را در پاسخ ارائه دهد. توجه داشته باشید که ارائه مسیرهای جایگزین ممکن است زمان پاسخگویی از سرور را افزایش دهد. این فقط برای درخواست های بدون ایستگاه های بین راهی در دسترس است.
  • avoidFerries ( اختیاری ) وقتی روی true تنظیم شود نشان می دهد که مسیر(های) محاسبه شده باید در صورت امکان از کشتی اجتناب کند.
  • avoidHighways ( اختیاری ) وقتی روی true تنظیم شود نشان می دهد که مسیر(های) محاسبه شده باید در صورت امکان از بزرگراه های اصلی اجتناب کند.
  • avoidTolls ( اختیاری ) وقتی روی true تنظیم شود نشان می دهد که مسیر(های) محاسبه شده باید در صورت امکان از جاده های عوارضی اجتناب کند.
  • region ( اختیاری ) کد منطقه را مشخص می کند که به عنوان مقدار دو کاراکتری ccTLD ("دامنه سطح بالا") مشخص شده است. (برای اطلاعات بیشتر به منطقه بایاس در زیر مراجعه کنید.)

در زیر نمونه ای DirectionsRequest آمده است:

{
  origin: 'Chicago, IL',
  destination: 'Los Angeles, CA',
  waypoints: [
    {
      location: 'Joplin, MO',
      stopover: false
    },{
      location: 'Oklahoma City, OK',
      stopover: true
    }],
  provideRouteAlternatives: false,
  travelMode: 'DRIVING',
  drivingOptions: {
    departureTime: new Date(/* now, or future date */),
    trafficModel: 'pessimistic'
  },
  unitSystem: google.maps.UnitSystem.IMPERIAL
}

حالت های سفر

هنگام محاسبه مسیرها، باید مشخص کنید که از کدام حالت حمل و نقل استفاده کنید. حالت های سفر زیر در حال حاضر پشتیبانی می شوند:

  • DRIVING ( پیش فرض ) جهت های رانندگی استاندارد را با استفاده از شبکه جاده نشان می دهد.
  • BICYCLING از طریق مسیرهای دوچرخه و خیابان‌های ترجیحی، مسیرهای دوچرخه‌سواری را درخواست می‌کند.
  • TRANSIT از طریق مسیرهای حمل و نقل عمومی، مسیرها را درخواست می کند.
  • WALKING مسیرهای پیاده روی را از طریق مسیرهای عابر پیاده و پیاده روها درخواست می کند.

برای تعیین میزان پشتیبانی یک کشور از مسیرها ، با جزئیات پوشش پلتفرم Google Maps مشورت کنید. اگر برای منطقه‌ای که این نوع جهت در دسترس نیست، دستورالعمل‌ها را درخواست کنید، پاسخ DirectionsStatus =" ZERO_RESULTS " را برمی‌گرداند.

توجه : مسیرهای پیاده روی ممکن است شامل مسیرهای عابر پیاده واضح نباشد، بنابراین مسیرهای پیاده روی هشدارهایی را در DirectionsResult نشان می دهند. این هشدارها باید همیشه به کاربر نمایش داده شود. اگر DirectionsRenderer پیش‌فرض استفاده نمی‌کنید، مسئولیت اطمینان از نمایش هشدارها بر عهده شماست.

گزینه های حمل و نقل

گزینه های موجود برای درخواست مسیرها بین حالت های سفر متفاوت است. هنگام درخواست مسیرهای حمل‌ونقل، گزینه‌های avoidHighways ، avoidTolls ، waypoints[] و optimizeWaypoints نادیده گرفته می‌شوند. می‌توانید از طریق شیء TransitOptions ، گزینه‌های مسیریابی خاص ترانزیت را مشخص کنید.

مسیرهای حمل و نقل به زمان حساس هستند. مسیرها فقط برای چند وقت در آینده بازگردانده خواهند شد.

شیء TransitOptions حاوی فیلدهای زیر است:

{
  arrivalTime: Date,
  departureTime: Date,
  modes[]: TransitMode,
  routingPreference: TransitRoutePreference
}

این فیلدها در زیر توضیح داده شده است:

  • arrivalTime ( اختیاری ) زمان مورد نظر رسیدن را به عنوان شیء Date مشخص می کند. اگر زمان ورود مشخص شده باشد، زمان حرکت نادیده گرفته می شود.
  • departureTime ( اختیاری ) زمان مورد نظر خروج را به عنوان شیء Date مشخص می کند. اگر arrivalTime مشخص شده باشد departureTime نادیده گرفته می شود. در صورتی که هیچ مقداری برای departureTime و یا arrivalTime تعیین نشده باشد، تا کنون (یعنی زمان فعلی) پیش‌فرض می‌شود.
  • modes[] ( اختیاری ) آرایه‌ای است که شامل یک یا چند شیء TransitMode است. این فیلد ممکن است فقط در صورتی گنجانده شود که درخواست شامل یک کلید API باشد. هر TransitMode یک حالت انتقال ترجیحی را مشخص می کند. مقادیر زیر مجاز است:
    • BUS نشان می دهد که مسیر محاسبه شده باید سفر با اتوبوس را ترجیح دهد.
    • RAIL نشان می دهد که مسیر محاسبه شده باید سفر با قطار، تراموا، قطار سبک و مترو را ترجیح دهد.
    • SUBWAY نشان می دهد که مسیر محاسبه شده باید سفر با مترو را ترجیح دهد.
    • TRAIN نشان می دهد که مسیر محاسبه شده باید سفر با قطار را ترجیح دهد.
    • TRAM نشان می دهد که مسیر محاسبه شده باید سفر با تراموا و راه آهن سبک را ترجیح دهد.
  • routingPreference ( اختیاری ) اولویت ها را برای مسیرهای حمل و نقل مشخص می کند. با استفاده از این گزینه، به جای پذیرش بهترین مسیر پیش‌فرض انتخاب شده توسط API، می‌توانید گزینه‌های بازگشتی را سوگیری کنید. این فیلد ممکن است تنها در صورتی مشخص شود که درخواست شامل یک کلید API باشد. مقادیر زیر مجاز است:
    • FEWER_TRANSFERS نشان می دهد که مسیر محاسبه شده باید تعداد محدودی انتقال را ترجیح دهد.
    • LESS_WALKING نشان می دهد که مسیر محاسبه شده باید مقادیر محدودی پیاده روی را ترجیح دهد.

نمونه ای DirectionsRequest با حمل و نقل در زیر نشان داده شده است:

{
  origin: 'Hoboken NJ',
  destination: 'Carroll Gardens, Brooklyn',
  travelMode: 'TRANSIT',
  transitOptions: {
    departureTime: new Date(1337675679473),
    modes: ['BUS'],
    routingPreference: 'FEWER_TRANSFERS'
  },
  unitSystem: google.maps.UnitSystem.IMPERIAL
}

گزینه های رانندگی

می توانید از طریق شی DrivingOptions گزینه های مسیریابی را برای مسیرهای رانندگی مشخص کنید.

شی DrivingOptions شامل فیلدهای زیر است:

{
  departureTime: Date,
  trafficModel: TrafficModel
}

این فیلدها در زیر توضیح داده شده است:

  • departureTime ( برای معتبر بودن شیء drivingOptions مورد نیاز است ) زمان مورد نظر خروج را به عنوان شیء Date مشخص می کند. مقدار باید روی زمان فعلی یا مدتی در آینده تنظیم شود. نمی تواند در گذشته باشد. (API همه تاریخ‌ها را به UTC تبدیل می‌کند تا از مدیریت یکنواخت در مناطق زمانی اطمینان حاصل کند.) برای مشتریان پلتفرم Google Maps Premium، اگر departureTime را در درخواست لحاظ کنید، API بهترین مسیر را با توجه به شرایط ترافیکی مورد انتظار در آن زمان برمی‌گرداند، و شامل زمان پیش‌بینی‌شده در ترافیک ( duration_in_traffic ) در پاسخ می‌شود. اگر زمان حرکت را مشخص نکنید (یعنی اگر درخواست شامل drivingOptions نباشد)، مسیر برگشتی به طور کلی مسیر خوبی است بدون در نظر گرفتن شرایط ترافیک.
  • trafficModel ( اختیاری ) مفروضاتی را مشخص می کند که باید هنگام محاسبه زمان در ترافیک استفاده شود. این تنظیم بر مقدار بازگشتی در قسمت duration_in_traffic در پاسخ تأثیر می‌گذارد که شامل زمان پیش‌بینی‌شده در ترافیک بر اساس میانگین‌های تاریخی است. پیش فرض به bestguess . مقادیر زیر مجاز است:
    • bestguess (پیش‌فرض) نشان می‌دهد که duration_in_traffic بازگشتی باید بهترین تخمین زمان سفر با توجه به آنچه در مورد شرایط ترافیک تاریخی و ترافیک زنده شناخته شده است باشد. هرچه departureTime به زمان حال نزدیک‌تر باشد، ترافیک زنده اهمیت بیشتری پیدا می‌کند.
    • pessimistic نشان می دهد که duration_in_traffic بازگشتی_in_traffic باید بیشتر از زمان واقعی سفر در بیشتر روزها باشد، اگرچه روزهای گاه به گاه با شرایط ترافیکی به خصوص بد ممکن است از این مقدار فراتر رود.
    • optimistic نشان می‌دهد که duration_in_traffic برگشتی باید در بیشتر روزها کوتاه‌تر از زمان واقعی سفر باشد، اگرچه ممکن است روزهای گاه به گاه با شرایط ترافیکی خوب سریع‌تر از این مقدار باشد.

در زیر نمونه ای DirectionsRequest برای مسیرهای رانندگی آمده است:

{
  origin: 'Chicago, IL',
  destination: 'Los Angeles, CA',
  travelMode: 'DRIVING',
  drivingOptions: {
    departureTime: new Date(Date.now() + N),  // for the time N milliseconds from now.
    trafficModel: 'optimistic'
  }
}

سیستم های واحد

به طور پیش فرض، جهت ها با استفاده از سیستم واحد کشور یا منطقه مبدا محاسبه و نمایش داده می شوند. (توجه: مبداها با استفاده از مختصات طول و عرض جغرافیایی به جای آدرس‌ها بیان می‌شوند که همیشه واحدهای متریک پیش‌فرض هستند.) به عنوان مثال، مسیری از "Chicago, IL" به "Toronto, ONT" نتایج را برحسب مایل نشان می‌دهد، در حالی که مسیر معکوس نتایج را نشان می‌دهد. در کیلومتر با استفاده از یکی از مقادیر UnitSystem زیر می‌توانید این سیستم واحد را با تنظیم صریح یکی در داخل درخواست لغو کنید:

  • UnitSystem.METRIC استفاده از سیستم متریک را مشخص می کند. فاصله ها با استفاده از کیلومتر نشان داده می شوند.
  • UnitSystem.IMPERIAL استفاده از سیستم امپریال (انگلیسی) را مشخص می کند. فاصله ها با استفاده از مایل نشان داده می شوند.

توجه: این تنظیم سیستم واحد فقط بر متن نمایش داده شده به کاربر تأثیر می گذارد. نتیجه جهت ها همچنین حاوی مقادیر فاصله است که به کاربر نشان داده نمی شود و همیشه بر حسب متر بیان می شود.

جهت گیری منطقه برای مسیرها

سرویس Google Maps API Directions نتایج آدرس را تحت تأثیر دامنه (منطقه یا کشور) که بوت استرپ جاوا اسکریپت را از آنجا بارگیری کرده اید، برمی گرداند. (از آنجایی که اکثر کاربران https://maps.googleapis.com/ را بارگذاری می کنند، این یک دامنه ضمنی را برای ایالات متحده تنظیم می کند.) اگر بوت استرپ را از دامنه پشتیبانی شده دیگری بارگیری کنید، نتایج تحت تأثیر آن دامنه دریافت خواهید کرد. برای مثال، جستجوهای «سان فرانسیسکو» ممکن است نتایج متفاوتی را از برنامه‌هایی که https://maps.googleapis.com/ (ایالات متحده آمریکا) بارگیری می‌کنند، نسبت به برنامه‌هایی که http://maps.google.es/ (اسپانیا) بارگیری می‌کنند، نشان دهد.

همچنین می توانید سرویس Directions را طوری تنظیم کنید که با استفاده از پارامتر region ، نتایج بایاس به یک منطقه خاص را بازگرداند. این پارامتر یک کد منطقه ای را می گیرد که به عنوان یک زیربرچسب منطقه یونیکد دو کاراکتری (غیر عددی) مشخص شده است. در بیشتر موارد، این برچسب‌ها مستقیماً به مقادیر دو کاراکتری ccTLD ("دامنه سطح بالا") مانند "uk" در "co.uk" نگاشت می‌شوند. در برخی موارد، تگ region از کدهای ISO-3166-1 نیز پشتیبانی می کند، که گاهی اوقات با مقادیر ccTLD متفاوت است (برای مثال "GB" برای "بریتانیا بزرگ").

هنگام استفاده از پارامتر region :

  • فقط یک کشور یا منطقه را مشخص کنید. چندین مقدار نادیده گرفته می شوند و ممکن است منجر به یک درخواست ناموفق شود.
  • فقط از زیربرچسب های منطقه دو کاراکتری (فرمت Unicode CLDR) استفاده کنید. همه ورودی های دیگر منجر به خطا می شوند.

سوگیری منطقه فقط برای کشورها و مناطق حمایت کننده جهت ها پشتیبانی می شود. برای مشاهده پوشش بین المللی برای Directions API با جزئیات پوشش پلت فرم Google Maps مشورت کنید.

رندر دستورالعمل

شروع یک درخواست جهت به DirectionsService با متد route() مستلزم ارسال یک فراخوان است که پس از تکمیل درخواست سرویس اجرا می شود. این فراخوانی یک DirectionsResult و یک کد DirectionsStatus را در پاسخ برمی گرداند.

پرس و جو وضعیت مسیرها

DirectionsStatus ممکن است مقادیر زیر را برگرداند:

  • OK نشان می‌دهد که پاسخ حاوی DirectionsResult معتبری است.
  • NOT_FOUND نشان می‌دهد که حداقل یکی از مکان‌های مشخص‌شده در مبدأ، مقصد یا ایستگاه‌های بین درخواست نمی‌تواند جغرافیایی کدگذاری شود.
  • ZERO_RESULTS نشان می دهد که هیچ مسیری بین مبدا و مقصد یافت نمی شود.
  • MAX_WAYPOINTS_EXCEEDED نشان می‌دهد که تعداد زیادی فیلد DirectionsWaypoint در DirectionsRequest ارائه شده است. به بخش زیر در مورد محدودیت برای نقاط راه مراجعه کنید.
  • MAX_ROUTE_LENGTH_EXCEEDED نشان می‌دهد که مسیر درخواستی بسیار طولانی است و قابل پردازش نیست. این خطا زمانی رخ می دهد که جهت های پیچیده تری برگردانده شوند. سعی کنید تعداد نقاط بین راه، پیچ ها یا دستورالعمل ها را کاهش دهید.
  • INVALID_REQUEST نشان می دهد که DirectionsRequest ارائه شده نامعتبر بوده است. شایع‌ترین دلایل این کد خطا، درخواست‌هایی هستند که مبدأ یا مقصد یا درخواست حمل‌ونقل شامل نقاط بین راه را ندارند.
  • OVER_QUERY_LIMIT نشان می دهد که صفحه وب درخواست های زیادی را در بازه زمانی مجاز ارسال کرده است.
  • REQUEST_DENIED نشان می دهد که صفحه وب مجاز به استفاده از سرویس مسیرها نیست.
  • UNKNOWN_ERROR نشان می‌دهد که درخواست جهت به دلیل خطای سرور قابل پردازش نیست. اگر دوباره تلاش کنید ممکن است درخواست با موفقیت انجام شود.

قبل از پردازش نتیجه، باید با بررسی این مقدار اطمینان حاصل کنید که پرس و جوی جهت ها نتایج معتبری را ارائه می دهد.

نمایش نتیجه Directions

DirectionsResult حاوی نتیجه پرس و جو جهت ها است که می توانید آن را خودتان مدیریت کنید یا به یک شی DirectionsRenderer ارسال کنید، که می تواند به طور خودکار نمایش نتیجه را روی نقشه انجام دهد.

برای نمایش DirectionsResult با استفاده از DirectionsRenderer ، باید موارد زیر را انجام دهید:

  1. یک شی DirectionsRenderer ایجاد کنید.
  2. setMap() در رندر فراخوانی کنید تا به نقشه ارسال شده متصل شود.
  3. setDirections() در رندر فراخوانی کنید و همان طور که در بالا ذکر شد DirectionsResult را ارسال کنید. از آنجایی که رندر یک MVCObject است، به طور خودکار هر گونه تغییر در ویژگی های آن را شناسایی می کند و زمانی که جهت های مرتبط با آن تغییر کرد، نقشه را به روز می کند.

مثال زیر جهت‌های بین دو مکان در مسیر 66 را محاسبه می‌کند، جایی که مبدا و مقصد با مقادیر داده‌شده "start" و "end" در لیست‌های کشویی تنظیم می‌شوند. DirectionsRenderer نمایش چند خط بین مکان‌های مشخص شده و قرار دادن نشانگرها در مبدا، مقصد و هر نقطه‌ای را در صورت وجود کنترل می‌کند.

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
    origin: start,
    destination: end,
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(result, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(result);
    }
  });
}

در بدنه HTML:

<div>
<strong>Start: </strong>
<select id="start" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
<strong>End: </strong>
<select id="end" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
</div>

مشاهده نمونه

مثال زیر مسیرهایی را با استفاده از حالت‌های مختلف سفر بین Haight-Ashbury تا Ocean Beach در سانفرانسیسکو، CA نشان می‌دهد:

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var haight = new google.maps.LatLng(37.7699298, -122.4469157);
  var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
  var mapOptions = {
    zoom: 14,
    center: haight
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
}

function calcRoute() {
  var selectedMode = document.getElementById('mode').value;
  var request = {
      origin: haight,
      destination: oceanBeach,
      // Note that JavaScript allows us to access the constant
      // using square brackets and a string value as its
      // "property."
      travelMode: google.maps.TravelMode[selectedMode]
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(response);
    }
  });
}

در بدنه HTML:

<div>
<strong>Mode of Travel: </strong>
<select id="mode" onchange="calcRoute();">
  <option value="DRIVING">Driving</option>
  <option value="WALKING">Walking</option>
  <option value="BICYCLING">Bicycling</option>
  <option value="TRANSIT">Transit</option>
</select>
</div>

مشاهده نمونه

یک DirectionsRenderer نه تنها نمایش چند خط و هر نشانگر مرتبط را کنترل می کند، بلکه می تواند نمایش متنی جهت ها را نیز به صورت مجموعه ای از مراحل مدیریت کند. برای انجام این کار، setPanel() در DirectionsRenderer خود فراخوانی کنید و <div> را برای نمایش این اطلاعات ارسال کنید. انجام این کار همچنین تضمین می کند که اطلاعات مربوط به حق نسخه برداری و هرگونه هشداری را که ممکن است با نتیجه مرتبط باشد نمایش دهید.

دستورالعمل‌های متنی با استفاده از تنظیمات زبان ترجیحی مرورگر یا زبانی که هنگام بارگیری جاوا اسکریپت API با استفاده از پارامتر language مشخص شده است، ارائه می‌شود. (برای اطلاعات بیشتر، به محلی سازی مراجعه کنید. ) در مورد جهت های حمل و نقل، زمان در منطقه زمانی در آن ایستگاه حمل و نقل نمایش داده می شود.

مثال زیر با آنچه در بالا نشان داده شده است یکسان است، اما شامل یک پانل <div> است که در آن جهت ها نمایش داده می شود:

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
  directionsRenderer.setPanel(document.getElementById('directionsPanel'));
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
    origin:start,
    destination:end,
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(response);
    }
  });
}

در بدنه HTML:

<div id="map" style="float:left;width:70%;height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height:100%"></div>

مشاهده نمونه

شی DirectionsResult

هنگام ارسال یک درخواست جهت به DirectionsService ، پاسخی متشکل از یک کد وضعیت و یک نتیجه دریافت می کنید که یک شی DirectionsResult است. DirectionsResult یک شی به معنای واقعی کلمه با فیلدهای زیر است:

  • geocoded_waypoints[] حاوی آرایه‌ای از اشیاء DirectionsGeocodedWaypoint است که هر کدام حاوی جزئیاتی در مورد کدگذاری جغرافیایی مبدا، مقصد و ایستگاه‌های بین راهی است.
  • routes[] حاوی آرایه ای از اشیاء DirectionsRoute است. هر مسیر راهی را برای رسیدن از مبدا به مقصد ارائه شده در DirectionsRequest نشان می دهد. به طور کلی، تنها یک مسیر برای هر درخواست داده شده برگردانده می شود، مگر اینکه قسمت provideRouteAlternatives درخواست روی true تنظیم شده باشد که در آن مسیرهای متعددی ممکن است برگردانده شوند.

نکته: ویژگی via_waypoint در مسیرهای جایگزین منسوخ شده است. نسخه 3.27 آخرین نسخه API است که از طریق ایستگاه های بین راه در مسیرهای جایگزین، موارد اضافی را اضافه می کند. برای نسخه‌های 3.28 و بالاتر API، می‌توانید با غیرفعال کردن کشیدن مسیرهای جایگزین، مسیرهای قابل کشیدن را با استفاده از سرویس Directions پیاده‌سازی کنید. فقط مسیر اصلی باید قابل کشیدن باشد. کاربران می توانند مسیر اصلی را تا زمانی که با یک مسیر جایگزین مطابقت داشته باشد بکشند.

مسیرهای مسیرهای جغرافیایی کد شده

یک DirectionsGeocodedWaypoint حاوی جزئیاتی درباره ژئوکدگذاری مبدا، مقصد و ایستگاه های بین راهی است.

DirectionsGeocodedWaypoint یک شی با فیلدهای زیر است:

  • geocoder_status کد وضعیت حاصل از عملیات geocoding را نشان می دهد. این فیلد ممکن است حاوی مقادیر زیر باشد.
    • "OK" نشان می دهد که هیچ خطایی رخ نداده است. آدرس با موفقیت تجزیه شد و حداقل یک ژئوکد برگردانده شد.
    • "ZERO_RESULTS" نشان می دهد که ژئوکد موفقیت آمیز بود اما هیچ نتیجه ای نداشت. این ممکن است در صورتی رخ دهد که geocoder یک address غیرموجود ارسال شده باشد.
  • partial_match نشان می دهد که geocoder مطابقت دقیقی با درخواست اصلی برنگردانده است، اگرچه می تواند بخشی از آدرس درخواستی را مطابقت دهد. ممکن است بخواهید درخواست اصلی برای غلط املایی و/یا آدرس ناقص را بررسی کنید.

    تطابق جزئی اغلب برای آدرس‌های خیابانی رخ می‌دهد که در محلی که در درخواست عبور می‌کنید وجود ندارد. زمانی که درخواستی با دو یا چند مکان در همان محل مطابقت داشته باشد، مسابقات جزئی نیز ممکن است برگردانده شوند. به عنوان مثال، "Hillpar St, Bristol, UK" یک مسابقه جزئی را برای خیابان هنری و خیابان هنریتا برمی گرداند. توجه داشته باشید که اگر یک درخواست شامل یک جزء آدرس غلط املایی باشد، سرویس کدگذاری جغرافیایی ممکن است یک آدرس جایگزین پیشنهاد دهد. پیشنهادهایی که از این طریق فعال می شوند نیز به عنوان تطابق جزئی علامت گذاری می شوند.

  • place_id یک شناسه منحصر به فرد یک مکان است که می تواند با سایر API های Google استفاده شود. برای مثال، می‌توانید از place_id با کتابخانه Google Places API برای دریافت جزئیات یک کسب‌وکار محلی، مانند شماره تلفن، ساعات کاری، نظرات کاربران و موارد دیگر استفاده کنید. نمای کلی شناسه مکان را ببینید.
  • types[] آرایه ای است که نوع نتیجه برگشتی را نشان می دهد. این آرایه حاوی مجموعه‌ای از صفر یا چند تگ است که نوع ویژگی برگردانده شده در نتیجه را مشخص می‌کند. برای مثال، ژئوکد «شیکاگو» «محلی» را برمی‌گرداند که نشان می‌دهد «شیکاگو» یک شهر است، و همچنین «سیاسی» را برمی‌گرداند که نشان می‌دهد یک نهاد سیاسی است.

مسیرهای مسیرها

توجه : شیء قدیمی DirectionsTrip به DirectionsRoute تغییر نام داده است. توجه داشته باشید که یک مسیر اکنون به کل سفر شروع تا پایان اشاره دارد، نه صرفاً یک مرحله از سفر والدین.

DirectionsRoute حاوی یک نتیجه واحد از مبدا و مقصد مشخص شده است. این مسیر ممکن است از یک یا چند پا (از نوع DirectionsLeg ) تشکیل شده باشد که بستگی به این دارد که آیا نقطه‌ای بین راه مشخص شده است یا خیر. همچنین، مسیر همچنین حاوی اطلاعات حق چاپ و هشدار است که باید علاوه بر اطلاعات مسیریابی به کاربر نمایش داده شود.

DirectionsRoute یک شی به معنای واقعی کلمه با فیلدهای زیر است:

  • legs[] حاوی آرایه ای از اشیاء DirectionsLeg است که هر کدام حاوی اطلاعاتی در مورد یک قسمت از مسیر، از دو مکان در مسیر معین است. برای هر نقطه راه یا مقصد مشخص شده یک پایه جداگانه وجود خواهد داشت. (مسیری که هیچ نقطه بین راه ندارد دقیقاً شامل یک DirectionsLeg خواهد بود.) هر پا از یک سری مراحل DirectionStep تشکیل شده است.
  • waypoint_order حاوی آرایه‌ای است که ترتیب هر نقطه‌ای را در مسیر محاسبه‌شده نشان می‌دهد. اگر DirectionsRequest optimizeWaypoints: true ارسال شود، این آرایه ممکن است حاوی یک ترتیب تغییر یافته باشد.
  • overview_path شامل آرایه‌ای از LatLng است که یک مسیر تقریبی (هموار) از جهت‌های حاصل را نشان می‌دهد.
  • overview_polyline شامل یک شی points منفرد است که نمایش چند خطی رمزگذاری شده مسیر را در خود دارد. این چند خط یک مسیر تقریبی (هموار) جهت های حاصل است.
  • bounds حاوی یک LatLngBounds است که مرزهای چند خط را در این مسیر مشخص نشان می دهد.
  • copyrights حاوی متن حق چاپ است که برای این مسیر نمایش داده می شود.
  • warnings[] حاوی آرایه ای از اخطارها است که هنگام نمایش این جهت ها نمایش داده می شود. اگر از شیء ارائه شده DirectionsRenderer استفاده نمی کنید، باید خودتان این هشدارها را مدیریت کرده و نمایش دهید.
  • fare شامل کل کرایه (یعنی کل هزینه بلیط) در این مسیر است. این دارایی فقط برای درخواست های حمل و نقل و فقط برای مسیرهایی که اطلاعات کرایه برای تمام مسیرهای حمل و نقل در دسترس است، بازگردانده می شود. اطلاعات شامل:
    • currency : یک کد ارز ISO 4217 که واحد پولی را نشان می دهد که مبلغ با آن بیان می شود.
    • value : کل مبلغ کرایه، به ارز مشخص شده در بالا.

مسیرها پاها

توجه : شیء قدیمی DirectionsRoute به DirectionsLeg تغییر نام داده است.

DirectionsLeg یک مرحله از سفر را از مبدا تا مقصد در مسیر محاسبه شده تعریف می کند. برای مسیرهایی که حاوی هیچ نقطه ای نیستند، مسیر از یک "پایه" تشکیل می شود، اما برای مسیرهایی که یک یا چند ایستگاه بین راهی را تعریف می کنند، مسیر شامل یک یا چند پا است که مربوط به قسمت های خاص سفر است.

DirectionsLeg یک شی به معنای واقعی کلمه با فیلدهای زیر است:

  • steps[] حاوی آرایه ای از اشیاء DirectionsStep است که اطلاعات مربوط به هر مرحله جداگانه از مرحله سفر را نشان می دهد.
  • distance کل مسافت طی شده توسط این پا را به عنوان یک شی Distance به شکل زیر نشان می دهد:

    • value فاصله را بر حسب متر نشان می دهد
    • text حاوی یک نمایش رشته ای از فاصله است که به طور پیش فرض در واحدهای مورد استفاده در مبدا نمایش داده می شود. (به عنوان مثال، مایل ها برای هر مبدأ در ایالات متحده استفاده می شود.) شما می توانید این سیستم واحد را با تنظیم خاص یک UnitSystem در جستار اصلی لغو کنید. توجه داشته باشید که صرف نظر از سیستم واحدی که استفاده می کنید، فیلد distance.value همیشه حاوی مقداری است که بر حسب متر بیان می شود.

    اگر فاصله ناشناخته باشد، ممکن است این فیلدها تعریف نشده باشند.

  • duration کل مدت این پا را به عنوان یک شی Duration از فرم زیر نشان می دهد:

    • value مدت زمان را بر حسب ثانیه نشان می دهد.
    • text شامل نمایش رشته ای از مدت زمان است.

    اگر مدت زمان نامشخص باشد، ممکن است این فیلدها تعریف نشده باشند.

  • duration_in_traffic کل مدت این مرحله را با در نظر گرفتن شرایط ترافیک فعلی نشان می دهد. duration_in_traffic فقط در صورتی برگردانده می شود که همه موارد زیر درست باشد:

    • این درخواست شامل ایستگاه های توقف نیست. به این معنا که شامل نقاطی نمی‌شود که stopover در آن‌ها true است.
    • درخواست به طور خاص برای مسیرهای رانندگی است - mode روی driving تنظیم شده است.
    • departureTime به عنوان بخشی از قسمت drivingOptions در درخواست گنجانده شده است.
    • شرایط ترافیک برای مسیر درخواستی فراهم است.

    duration_in_traffic شامل فیلدهای زیر است:

    • value مدت زمان را بر حسب ثانیه نشان می دهد.
    • text حاوی نمایشی از مدت زمان قابل خواندن برای انسان است.
  • arrival_time شامل زمان تخمینی رسیدن برای این مرحله است. این دارایی فقط برای مسیرهای حمل و نقل بازگردانده می شود. نتیجه به عنوان یک شی Time با سه ویژگی برگردانده می شود:
    • زمان مشخص شده را به عنوان یک شیء Date جاوا اسکریپت value .
    • زمان مشخص شده را به عنوان یک رشته text . زمان در منطقه زمانی ایستگاه حمل و نقل نمایش داده می شود.
    • time_zone شامل منطقه زمانی این ایستگاه است. مقدار، نام منطقه زمانی است که در پایگاه داده منطقه زمانی IANA تعریف شده است، به عنوان مثال "America/New_York".
  • departure_time شامل زمان تخمینی حرکت برای این پا است که به عنوان یک شی Time مشخص شده است. departure_time فقط برای مسیرهای حمل‌ونقل عمومی در دسترس است.
  • start_location حاوی LatLng مبدا این پا است. از آنجا که سرویس وب Directions جهت‌ها را بین مکان‌ها با استفاده از نزدیک‌ترین گزینه حمل‌ونقل (معمولاً یک جاده) در نقطه شروع و پایان محاسبه می‌کند، اگر مثلاً جاده‌ای نزدیک مبدا نباشد، start_location ممکن است با مبدا ارائه‌شده این پا متفاوت باشد. .
  • end_location حاوی LatLng مقصد این قسمت است. از آنجایی که DirectionsService جهت‌های بین مکان‌ها را با استفاده از نزدیک‌ترین گزینه حمل‌ونقل (معمولاً یک جاده) در نقطه شروع و پایان محاسبه می‌کند، اگر مثلاً جاده‌ای نزدیک مقصد نباشد، end_location ممکن است با مقصد ارائه‌شده در این قسمت متفاوت باشد.
  • start_address حاوی آدرس قابل خواندن برای انسان (معمولاً آدرس خیابان) شروع این قسمت است.

    این محتوا باید همانطور که هست خوانده شود. آدرس فرمت شده را به صورت برنامه نویسی تجزیه نکنید.
  • end_address حاوی آدرس قابل خواندن برای انسان (معمولاً آدرس خیابان) انتهای این قسمت است.

    این محتوا باید همانطور که هست خوانده شود. آدرس فرمت شده را به صورت برنامه نویسی تجزیه نکنید.

مراحل دستورالعمل

DirectionsStep اتمی ترین واحد مسیر یک جهت است که شامل یک مرحله است که یک دستورالعمل خاص و منفرد را در سفر توصیف می کند. به عنوان مثال "در خیابان W. 4th به چپ بپیچید." مرحله نه تنها دستورالعمل را توصیف می کند، بلکه حاوی اطلاعات فاصله و مدت مربوط به نحوه ارتباط این مرحله با مرحله زیر است. به عنوان مثال، مرحله ای که به عنوان "ادغام در I-80 West" مشخص می شود ممکن است دارای مدت زمان "37 مایل" و "40 دقیقه" باشد که نشان می دهد مرحله بعدی 37 مایل/40 دقیقه از این مرحله است.

هنگام استفاده از سرویس مسیرها برای جستجوی مسیرهای حمل و نقل، آرایه مراحل شامل اطلاعات ویژه حمل و نقل اضافی در قالب یک شی transit خواهد بود. اگر مسیرها شامل چندین حالت حمل‌ونقل باشند، دستورالعمل‌های دقیق برای قدم‌های پیاده‌روی یا رانندگی در یک آرایه steps[] ارائه می‌شود. به عنوان مثال، یک گام پیاده‌روی شامل مسیرهایی از محل شروع و پایان است: "Walk to Innes Ave & Fitch St". این مرحله شامل مسیرهای پیاده‌روی دقیق برای آن مسیر در آرایه‌های steps[] می‌شود، مانند: «به سمت شمال غربی»، «به چپ روی آرلیوس واکر بپیچید» و «به سمت چپ به خیابان اینس بپیچید».

DirectionsStep یک شی به معنای واقعی کلمه با فیلدهای زیر است:

  • instructions حاوی دستورالعمل هایی برای این مرحله در یک رشته متنی است.
  • distance شامل مسافت طی شده توسط این مرحله تا مرحله بعدی به عنوان یک شی Distance است. (توضیحات را در DirectionsLeg بالا ببینید.) اگر فاصله ناشناخته باشد، ممکن است این فیلد تعریف نشده باشد.
  • duration شامل تخمینی از زمان مورد نیاز برای انجام مرحله، تا مرحله بعدی، به عنوان یک شی Duration است. (توضیحات را در DirectionsLeg بالا ببینید.) اگر مدت زمان نامشخص باشد، ممکن است این فیلد تعریف نشده باشد.
  • start_location حاوی LatLng جغرافیایی نقطه شروع این مرحله است.
  • end_location حاوی LatLng نقطه پایانی این مرحله است.
  • polyline شامل یک شی points واحد است که نمایش چند خطی رمزگذاری شده از مرحله را در خود دارد. این چند خط یک مسیر تقریبی (هموار) پله است.
  • steps[] یک شی لفظی DirectionsStep که حاوی دستورالعمل های دقیق برای قدم زدن یا رانندگی در مسیرهای حمل و نقل است. مراحل فرعی فقط برای مسیرهای حمل و نقل در دسترس هستند.
  • travel_mode شامل TravelMode مورد استفاده در این مرحله است. مسیرهای حمل و نقل ممکن است ترکیبی از مسیرهای پیاده روی و حمل و نقل باشد.
  • path شامل آرایه ای از LatLngs است که سیر این مرحله را توصیف می کند.
  • transit شامل اطلاعات خاص حمل و نقل، مانند زمان ورود و خروج، و نام خط حمل و نقل است.

اطلاعات ویژه حمل و نقل

مسیرهای حمل و نقل اطلاعات اضافی را که برای سایر روش های حمل و نقل مرتبط نیست، برمی گرداند. این ویژگی‌های اضافی از طریق شی TransitDetails در معرض دید قرار می‌گیرند که به عنوان ویژگی DirectionsStep برگردانده می‌شود. از شی TransitDetails می توانید به اطلاعات اضافی برای اشیاء TransitStop ، TransitLine ، TransitAgency و VehicleType دسترسی داشته باشید که در زیر توضیح داده شده است.

جزئیات حمل و نقل

شی TransitDetails ویژگی های زیر را نشان می دهد:

  • arrival_stop contains a TransitStop object representing the arrival station/stop with the following properties:
    • name the name of the transit station/stop. eg. "Union Square".
    • location the location of the transit station/stop, represented as a LatLng .
  • departure_stop contains a TransitStop object representing the departure station/stop.
  • arrival_time contains the arrival time, specified as a Time object with three properties:
    • value the time specified as a JavaScript Date object.
    • text the time specified as a string. The time is displayed in the time zone of the transit stop.
    • time_zone contains the time zone of this station. The value is the name of the time zone as defined in the IANA Time Zone Database , eg "America/New_York".
  • departure_time contains the departure time, specified as a Time object.
  • headsign specifies the direction in which to travel on this line, as it is marked on the vehicle or at the departure stop. This will often be the terminus station.
  • headway when available, this specifies the expected number of seconds between departures from the same stop at this time. For example, with a headway value of 600, you would expect a ten minute wait if you should miss your bus.
  • line contains a TransitLine object literal that contains information about the transit line used in this step. The TransitLine provides the name and operator of the line, along with other properties described in the TransitLine reference documentation.
  • num_stops contains the number of stops in this step. Includes the arrival stop, but not the departure stop. For example, if your directions involve leaving from Stop A, passing through stops B and C, and arriving at stop D, num_stops will return 3.

Transit Line

The TransitLine object exposes the following properties:

  • name contains the full name of this transit line. eg. "7 Avenue Express" or "14th St Crosstown".
  • short_name contains the short name of this transit line. This will normally be a line number, such as "2" or "M14".
  • agencies is an array containing a single TransitAgency object. The TransitAgency object provides information about the operator of this line, including the following properties:
    • name contains the name of the transit agency.
    • phone contains the phone number of the transit agency.
    • url contains the URL for the transit agency.

    Note : If you are rendering transit directions manually instead of using the DirectionsRenderer object, you must display the names and URLs of the transit agencies servicing the trip results.

  • url contains a URL for this transit line as provided by the transit agency.
  • icon contains a URL for the icon associated with this line. Most cities will use generic icons that vary by the type of vehicle. Some transit lines, such as the New York subway system, have icons specific to that line.
  • color contains the color commonly used in signage for this transit. The color will be specified as a hex string such as: #FF0033.
  • text_color contains the color of text commonly used for signage of this line. The color will be specified as a hex string.
  • vehicle contains a Vehicle object that includes the following properties:
    • name contains the name of the vehicle on this line. eg. "Subway."
    • type contains the type of vehicle used on this line. See the Vehicle Type documentation for a complete list of supported values.
    • icon contains a URL for the icon commonly associated with this vehicle type.
    • local_icon contains the URL for the icon associated with this vehicle type, based on the local transport signage.

Vehicle Type

The VehicleType object exposes the following properties:

Value Definition
VehicleType.RAIL Rail.
VehicleType.METRO_RAIL Light rail transit.
VehicleType.SUBWAY Underground light rail.
VehicleType.TRAM Above ground light rail.
VehicleType.MONORAIL Monorail.
VehicleType.HEAVY_RAIL Heavy rail.
VehicleType.COMMUTER_TRAIN Commuter rail.
VehicleType.HIGH_SPEED_TRAIN High speed train.
VehicleType.BUS Bus.
VehicleType.INTERCITY_BUS Intercity bus.
VehicleType.TROLLEYBUS Trolleybus.
VehicleType.SHARE_TAXI Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route.
VehicleType.FERRY Ferry.
VehicleType.CABLE_CAR A vehicle that operates on a cable, usually on the ground. Aerial cable cars may be of the type VehicleType.GONDOLA_LIFT .
VehicleType.GONDOLA_LIFT An aerial cable car.
VehicleType.FUNICULAR A vehicle that is pulled up a steep incline by a cable. A Funicular typically consists of two cars, with each car acting as a counterweight for the other.
VehicleType.OTHER All other vehicles will return this type.

Inspecting DirectionsResults

The DirectionsResults components — DirectionsRoute , DirectionsLeg , DirectionsStep and TransitDetails — may be inspected and used when parsing any directions response.

Important : If you are rendering transit directions manually instead of using the DirectionsRenderer object, you must display the names and URLs of the transit agencies servicing the trip results.

The following example plots walking directions to certain tourist attractions in New York City. We inspect the route's DirectionsStep to add markers for each step, and attach information to an InfoWindow with instructional text for that step.

Note : Since we are calculating walking directions, we also display any warnings to the user in a separate <div> panel.

var map;
var directionsRenderer;
var directionsService;
var stepDisplay;
var markerArray = [];

function initMap() {
  // Instantiate a directions service.
  directionsService = new google.maps.DirectionsService();

  // Create a map and center it on Manhattan.
  var manhattan = new google.maps.LatLng(40.7711329, -73.9741874);
  var mapOptions = {
    zoom: 13,
    center: manhattan
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  // Create a renderer for directions and bind it to the map.
  var rendererOptions = {
    map: map
  }
  directionsRenderer = new google.maps.DirectionsRenderer(rendererOptions)

  // Instantiate an info window to hold step text.
  stepDisplay = new google.maps.InfoWindow();
}

function calcRoute() {

  // First, clear out any existing markerArray
  // from previous calculations.
  for (i = 0; i < markerArray.length; i++) {
    markerArray[i].setMap(null);
  }

  // Retrieve the start and end locations and create
  // a DirectionsRequest using WALKING directions.
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin: start,
      destination: end,
      travelMode: 'WALKING'
  };

  // Route the directions and pass the response to a
  // function to create markers for each step.
  directionsService.route(request, function(response, status) {
    if (status == "OK") {
      var warnings = document.getElementById("warnings_panel");
      warnings.innerHTML = "" + response.routes[0].warnings + "";
      directionsRenderer.setDirections(response);
      showSteps(response);
    }
  });
}

function showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  var myRoute = directionResult.routes[0].legs[0];

  for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = new google.maps.Marker({
        position: myRoute.steps[i].start_point,
        map: map
      });
      attachInstructionText(marker, myRoute.steps[i].instructions);
      markerArray[i] = marker;
  }
}

function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

In the HTML body:

<div>
<strong>Start: </strong>
<select id="start">
  <option value="penn station, new york, ny">Penn Station</option>
  <option value="grand central station, new york, ny">Grand Central Station</option>
  <option value="625 8th Avenue New York NY 10018">Port Authority Bus Terminal</option>
  <option value="staten island ferry terminal, new york, ny">Staten Island Ferry Terminal</option>
  <option value="101 E 125th Street, New York, NY">Harlem - 125th St Station</option>
</select>
<strong>End: </strong>
<select id="end" onchange="calcRoute();">
  <option value="260 Broadway New York NY 10007">City Hall</option>
  <option value="W 49th St & 5th Ave, New York, NY 10020">Rockefeller Center</option>
  <option value="moma, New York, NY">MOMA</option>
  <option value="350 5th Ave, New York, NY, 10118">Empire State Building</option>
  <option value="253 West 125th Street, New York, NY">Apollo Theatre</option>
  <option value="1 Wall St, New York, NY">Wall St</option>
</select>
<div>

مشاهده نمونه

Using Waypoints in Routes

As noted within the DirectionsRequest , you may also specify waypoints (of type DirectionsWaypoint ) when calculating routes using the Directions service for walking, bicycling or driving directions. Waypoints are not available for transit directions. Waypoints allow you to calculate routes through additional locations, in which case the returned route passes through the given waypoints.

A waypoint consists of the following fields:

  • location (required) specifies the address of the waypoint.
  • stopover (optional) indicates whether this waypoint is a actual stop on the route ( true ) or instead only a preference to route through the indicated location ( false ). Stopovers are true by default.

By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the traveling salesperson problem .) Travel time is the primary factor which is optimized, but other factors such as distance, number of turns and many more may be taken into account when deciding which route is the most efficient. All waypoints must be stopovers for the Directions service to optimize their route.

If you instruct the Directions service to optimize the order of its waypoints, their order will be returned in the waypoint_order field within the DirectionsResult object.

The following example calculates cross-country routes across the United States using a variety of start points, end points, and waypoints. (To select multiple waypoints, press Ctrl-Click when selecting items within the list.) Note that we inspect the routes.start_address and routes.end_address to provide us with the text for each route's start and end point.

TypeScript

function initMap(): void {
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 6,
      center: { lat: 41.85, lng: -87.65 },
    }
  );

  directionsRenderer.setMap(map);

  (document.getElementById("submit") as HTMLElement).addEventListener(
    "click",
    () => {
      calculateAndDisplayRoute(directionsService, directionsRenderer);
    }
  );
}

function calculateAndDisplayRoute(
  directionsService: google.maps.DirectionsService,
  directionsRenderer: google.maps.DirectionsRenderer
) {
  const waypts: google.maps.DirectionsWaypoint[] = [];
  const checkboxArray = document.getElementById(
    "waypoints"
  ) as HTMLSelectElement;

  for (let i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected) {
      waypts.push({
        location: (checkboxArray[i] as HTMLOptionElement).value,
        stopover: true,
      });
    }
  }

  directionsService
    .route({
      origin: (document.getElementById("start") as HTMLInputElement).value,
      destination: (document.getElementById("end") as HTMLInputElement).value,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING,
    })
    .then((response) => {
      directionsRenderer.setDirections(response);

      const route = response.routes[0];
      const summaryPanel = document.getElementById(
        "directions-panel"
      ) as HTMLElement;

      summaryPanel.innerHTML = "";

      // For each route, display summary information.
      for (let i = 0; i < route.legs.length; i++) {
        const routeSegment = i + 1;

        summaryPanel.innerHTML +=
          "<b>Route Segment: " + routeSegment + "</b><br>";
        summaryPanel.innerHTML += route.legs[i].start_address + " to ";
        summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
        summaryPanel.innerHTML += route.legs[i].distance!.text + "<br><br>";
      }
    })
    .catch((e) => window.alert("Directions request failed due to " + status));
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

جاوا اسکریپت

function initMap() {
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 6,
    center: { lat: 41.85, lng: -87.65 },
  });

  directionsRenderer.setMap(map);
  document.getElementById("submit").addEventListener("click", () => {
    calculateAndDisplayRoute(directionsService, directionsRenderer);
  });
}

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  const waypts = [];
  const checkboxArray = document.getElementById("waypoints");

  for (let i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected) {
      waypts.push({
        location: checkboxArray[i].value,
        stopover: true,
      });
    }
  }

  directionsService
    .route({
      origin: document.getElementById("start").value,
      destination: document.getElementById("end").value,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING,
    })
    .then((response) => {
      directionsRenderer.setDirections(response);

      const route = response.routes[0];
      const summaryPanel = document.getElementById("directions-panel");

      summaryPanel.innerHTML = "";

      // For each route, display summary information.
      for (let i = 0; i < route.legs.length; i++) {
        const routeSegment = i + 1;

        summaryPanel.innerHTML +=
          "<b>Route Segment: " + routeSegment + "</b><br>";
        summaryPanel.innerHTML += route.legs[i].start_address + " to ";
        summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
        summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
      }
    })
    .catch((e) => window.alert("Directions request failed due to " + status));
}

window.initMap = initMap;

Limits and Restrictions for Waypoints

The following usage limits and restrictions apply:

  • The maximum number of waypoints allowed when using the Directions service in the Maps JavaScript API is 25, plus the origin and destination. The limits are the same for the Directions API web service .
  • For the Directions API web service , customers are allowed 25 waypoints, plus the origin, and destination.
  • Google Maps Platform Premium Plan customers are allowed 25 waypoints, plus the origin, and destination.
  • Waypoints are not supported for transit directions.

Draggable Directions

Users may modify cycling, walking or driving directions displayed using a DirectionsRenderer dynamically if they are draggable , allowing a user to select and alter routes by clicking and dragging the resulting paths on the map. You indicate whether a renderer's display allows draggable directions by setting its draggable property to true . Transit directions cannot be made draggable.

When directions are draggable, a user may select any point on the path (or waypoint) of the rendered result and move the indicated component to a new location. The DirectionsRenderer will dynamically update to show the modified path. Upon release, a transitional waypoint will be added to the map (indicated by a small white marker). Selecting and moving a path segment will alter that leg of the route, while selecting and moving a waypoint marker (including start and end points) will alter the legs of the route passing through that waypoint.

Because draggable directions are modified and rendered client-side, you may wish to monitor and handle the directions_changed event on the DirectionsRenderer to be notified when the user has modified the displayed directions.

The following code shows a trip from Perth on the west coast of Australia to Sydney on the east coast. The code monitors the directions_changed event to update the total distance of all legs of the journey.

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -24.345, lng: 134.46 }, // Australia.
    }
  );

  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map,
    panel: document.getElementById("panel") as HTMLElement,
  });

  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
    }
  });

  displayRoute(
    "Perth, WA",
    "Sydney, NSW",
    directionsService,
    directionsRenderer
  );
}

function displayRoute(
  origin: string,
  destination: string,
  service: google.maps.DirectionsService,
  display: google.maps.DirectionsRenderer
) {
  service
    .route({
      origin: origin,
      destination: destination,
      waypoints: [
        { location: "Adelaide, SA" },
        { location: "Broken Hill, NSW" },
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
    })
    .then((result: google.maps.DirectionsResult) => {
      display.setDirections(result);
    })
    .catch((e) => {
      alert("Could not display directions due to: " + e);
    });
}

function computeTotalDistance(result: google.maps.DirectionsResult) {
  let total = 0;
  const myroute = result.routes[0];

  if (!myroute) {
    return;
  }

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i]!.distance!.value;
  }

  total = total / 1000;
  (document.getElementById("total") as HTMLElement).innerHTML = total + " km";
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

جاوا اسکریپت

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -24.345, lng: 134.46 }, // Australia.
  });
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map,
    panel: document.getElementById("panel"),
  });

  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
    }
  });
  displayRoute(
    "Perth, WA",
    "Sydney, NSW",
    directionsService,
    directionsRenderer
  );
}

function displayRoute(origin, destination, service, display) {
  service
    .route({
      origin: origin,
      destination: destination,
      waypoints: [
        { location: "Adelaide, SA" },
        { location: "Broken Hill, NSW" },
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
    })
    .then((result) => {
      display.setDirections(result);
    })
    .catch((e) => {
      alert("Could not display directions due to: " + e);
    });
}

function computeTotalDistance(result) {
  let total = 0;
  const myroute = result.routes[0];

  if (!myroute) {
    return;
  }

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }

  total = total / 1000;
  document.getElementById("total").innerHTML = total + " km";
}

window.initMap = initMap;
مشاهده نمونه

Sample را امتحان کنید