Gathering detailed insights and metrics for react-native-maps-directions-via-server
Gathering detailed insights and metrics for react-native-maps-directions-via-server
Gathering detailed insights and metrics for react-native-maps-directions-via-server
Gathering detailed insights and metrics for react-native-maps-directions-via-server
Directions Component for `react-native-maps`
npm install react-native-maps-directions-via-server
Typescript
Module System
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
153 Commits
1 Branches
1 Contributors
Updated on May 20, 2025
Latest Version
1.1.1
Package Id
react-native-maps-directions-via-server@1.1.1
Unpacked Size
44.93 kB
Size
12.19 kB
File Count
7
NPM Version
10.8.2
Node Version
18.20.6
Published on
May 20, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
No dependencies detected.
react-native-maps-directions-via-server
This component is built based on react-native-maps-directions, with changes below:
apikey
being compromised on the app side.directionsServiceBaseUrl
has been marked as a required parameter, as direction requests will be sent to the URL specified by it.headers
has been added as an optional parameter, works together with directionsServiceBaseUrl
, for authenticating if necessary.BTW, these changes addressed the issue mentioned at https://github.com/bramus/react-native-maps-directions/issues/84.
Install react-native-maps-directions
as a dependency using either
npm install react-native-maps-directions-via-server
yarn add react-native-maps-directions-via-server
Since the map directions feature in this library requires server-side implementation, before wiring it up in React Native, you'll must have server side ready. And the implementation at server-side is as simple as forwarding the request to google's server by appending the apiKey param to the request.
Server side:
Have a RESTful endpoint for forwarding the request to Google.
Here is a basic setup of endpoint at local http://10.2.97.131:3000/maps/api/directions/json
:
1const GOOGLE_API_KEY = "YOUR_GOOGLE_API_KEY"; 2 3const http = require("http"); 4const https = require("https"); 5const url = require("url"); 6const querystring = require("querystring"); // for handling query params 7 8const hostname = "0.0.0.0"; 9const port = 3000; 10 11const server = http.createServer((req, res) => { 12 const parsedUrl = url.parse(req.url, true); 13 const pathname = parsedUrl.pathname; 14 15 if (req.method === "GET" && pathname === "/maps/api/directions/json") { 16 const originalQuery = parsedUrl.query; 17 18 // ✅ Inject API key (override if client included it) 19 const queryWithKey = { 20 ...originalQuery, 21 key: GOOGLE_API_KEY, 22 }; 23 24 const queryString = querystring.stringify(queryWithKey); 25 const googleUrl = `https://maps.googleapis.com/maps/api/directions/json?${queryString}`; 26 27 let responded = false; 28 29 const proxyReq = https.get(googleUrl, (googleRes) => { 30 let data = ""; 31 32 googleRes.on("data", (chunk) => { 33 data += chunk; 34 }); 35 36 googleRes.on("end", () => { 37 if (!responded) { 38 responded = true; 39 res.statusCode = googleRes.statusCode; 40 res.setHeader("Content-Type", "application/json"); 41 res.end(data); 42 } 43 }); 44 }); 45 46 proxyReq.on("error", (err) => { 47 if (!responded) { 48 responded = true; 49 res.statusCode = 500; 50 res.setHeader("Content-Type", "application/json"); 51 res.end( 52 JSON.stringify({ 53 error: "Failed to fetch from Google Maps API", 54 details: err.message, 55 }) 56 ); 57 } else { 58 console.error("Unhandled proxy error after response:", err.message); 59 } 60 }); 61 } else { 62 res.statusCode = 404; 63 res.setHeader("Content-Type", "application/json"); 64 res.end(JSON.stringify({ error: "Not Found" })); 65 } 66}); 67 68server.listen(port, hostname, () => { 69 console.log(`Proxy server running at http://${hostname}:${port}/`); 70});
Run the command to start it up:
1node server.js
In React Native:
1import MapViewDirections from 'react-native-maps-directions-via-server'; 2 3const origin = {latitude: 37.3318456, longitude: -122.0296002}; 4const destination = {latitude: 37.771707, longitude: -122.4053769}; 5const directionsServiceBaseUrl = 'http://10.2.97.131:3000/maps/api/directions/json'; 6 7<MapView initialRegion={…}> 8 <MapViewDirections 9 key={index} 10 origin={origin} 11 destination={destination} 12 directionsServiceBaseUrl={directionsServiceBaseUrl} 13 headers={headers} 14 strokeWidth={5} 15 strokeColor={strokeColor} 16 mode="DRIVING" 17 zIndex={zIndex} 18 /> 19</MapView>
Then you're good to go.
Directions component for react-native-maps
– Draw a route between two coordinates, powered by the Google Maps Directions API
Install react-native-maps-directions
as a dependency using either
npm install react-native-maps-directions
yarn add react-native-maps-directions
Import MapViewDirections
and render it as a child of a MapView
component. The mandatory MapViewDirections
props are:
origin
: The origin location to start routing fromdestination
: The destination location to start routing toapikey
: Your Google Maps Directions API Key (request one here; if you're using an existing Google Maps API Key make sure you've enabled the Google Maps Directions API for that key using the Google API Console).1import MapViewDirections from 'react-native-maps-directions'; 2 3const origin = {latitude: 37.3318456, longitude: -122.0296002}; 4const destination = {latitude: 37.771707, longitude: -122.4053769}; 5const GOOGLE_MAPS_APIKEY = '…'; 6 7<MapView initialRegion={…}> 8 <MapViewDirections 9 origin={origin} 10 destination={destination} 11 apikey={GOOGLE_MAPS_APIKEY} 12 /> 13</MapView>
Once the directions in between destination
and origin
has been fetched, a MapView.Polyline
between the two will be drawn. Whenever one of both changes, new directions will be fetched and rendered.
Prop | Type | Default | Note |
---|---|---|---|
origin | LatLng or String | The origin location to start routing from. | |
destination | LatLng or String | The destination location to start routing to. | |
apikey | String | Your Google Maps API Key (request one here; if you're using an existing Google Maps API Key make sure you've enabled the Google Maps Directions API for that key using the Google API Console by hitting the “Enable APIs and Services“ button). | |
waypoints | [LatLng or String ] | [] | Array of waypoints to use between origin and destination. |
language | String | "en" | The language to use when calculating directions. See here for more info. |
mode | String | "DRIVING" | Which transportation mode to use when calculating directions. Allowed values are "DRIVING" , "BICYCLING" , "WALKING" , and "TRANSIT" . (See here for more info). |
resetOnChange | boolean | true | Tweak if the rendered MapView.Polyline should reset or not when calculating the route between origin and destionation . Set to false if you see the directions line glitching. |
optimizeWaypoints | boolean | false | Set it to true if you would like Google Maps to re-order all the waypoints to optimize the route for the fastest route. Please be aware that if this option is enabled, you will be billed at a higher rate by Google as stated here. |
splitWaypoints | boolean | false | Directions API has a limit of 10 or 25 (depends on the billing plan) waypoints per route. When exceeding this limit you will be billed at a higher reate by Google. Set this to true if you would like to automatically split waypoints into multiple routes, thus bypassing this waypoints limit. |
directionsServiceBaseUrl | string | (Google's) | Base URL of the Directions Service (API) you are using. By default the Google Directions API is used ("https://maps.googleapis.com/maps/api/directions/json" ). Usually you won't need to change this. |
region | String | If you are using strings for origin or destination, sometimes you will get an incorrect route because Google Maps API needs the region where this places belong to. See here for more info. | |
precision | String | "low" | The precision level of detail of the drawn polyline. Allowed values are "high", and "low". Setting to "low" will yield a polyline that is an approximate (smoothed) path of the resulting directions. Setting to "high" may cause a hit in performance in case a complex route is returned. |
timePrecision | String | "none" | The timePrecision to get Realtime traffic info. Allowed values are "none", and "now". Defaults to "none". |
channel | String | null | If you include the channel parameter in your requests, you can generate a Successful Requests report that shows a breakdown of your application's API requests across different applications that use the same client ID (such as externally facing access vs. internally facing access). |
Since the result rendered on screen is a MapView.Polyline
component, all MapView.Polyline
props – except for coordinates
– are also accepted.
1<MapView initialRegion={…}> 2 <MapViewDirections 3 origin={origin} 4 destination={destination} 5 apikey={GOOGLE_MAPS_APIKEY} 6 strokeWidth={3} 7 strokeColor="hotpink" 8 /> 9</MapView>
origin
and destination
The values for the origin
and destination
props can take several forms. They can either be:
latitude
and longitude
keyslatitude
and longitude
values separated by a commaplace_id:
All examples below have the same origin
location, represented in the formats mentioned above:
1<MapViewDirections origin={{ latitude: 37.3317876, longitude: -122.0054812 }} destination="…" /> 2<MapViewDirections origin="37.3317876,-122.0054812" destination="…" /> 3<MapViewDirections origin="Apple Park Visitor Center" destination="…" /> 4<MapViewDirections origin="10600 N Tantau Ave, Cupertino, CA 95014, USA" destination="…" /> 5<MapViewDirections origin="place_id:ChIJW5i0tJC1j4ARoUGtkogTaUU" destination="…" />
Note: The origin
and destination
props don't need to use the same representation, you may mix them.
Tip: Don't forget to tweak the language
prop when using localized location names.
Event Name | Returns | Notes |
---|---|---|
onStart | { origin, destination, waypoints: [] } | Callback that is called when the routing has started. |
onReady | { distance: Number, duration: Number, coordinates: [], fare: Object, waypointOrder: [[]] } | Callback that is called when the routing has succesfully finished. Note: distance returned in kilometers and duration in minutes. |
onError | errorMessage | Callback that is called in case the routing has failed. |
This example will draw a route between AirBnB's Office and Apple's HQ
1import React, { Component } from "react"; 2import { Dimensions, StyleSheet } from "react-native"; 3import MapView from "react-native-maps"; 4import MapViewDirections from "react-native-maps-directions"; 5 6const { width, height } = Dimensions.get("window"); 7const ASPECT_RATIO = width / height; 8const LATITUDE = 37.771707; 9const LONGITUDE = -122.4053769; 10const LATITUDE_DELTA = 0.0922; 11const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; 12 13const GOOGLE_MAPS_APIKEY = "…"; 14 15class Example extends Component { 16 constructor(props) { 17 super(props); 18 19 // AirBnB's Office, and Apple Park 20 this.state = { 21 coordinates: [ 22 { 23 latitude: 37.3317876, 24 longitude: -122.0054812, 25 }, 26 { 27 latitude: 37.771707, 28 longitude: -122.4053769, 29 }, 30 ], 31 }; 32 33 this.mapView = null; 34 } 35 36 onMapPress = (e) => { 37 this.setState({ 38 coordinates: [...this.state.coordinates, e.nativeEvent.coordinate], 39 }); 40 }; 41 42 render() { 43 return ( 44 <MapView 45 initialRegion={{ 46 latitude: LATITUDE, 47 longitude: LONGITUDE, 48 latitudeDelta: LATITUDE_DELTA, 49 longitudeDelta: LONGITUDE_DELTA, 50 }} 51 style={StyleSheet.absoluteFill} 52 ref={(c) => (this.mapView = c)} 53 onPress={this.onMapPress} 54 > 55 {this.state.coordinates.map((coordinate, index) => ( 56 <MapView.Marker key={`coordinate_${index}`} coordinate={coordinate} /> 57 ))} 58 {this.state.coordinates.length >= 2 && ( 59 <MapViewDirections 60 origin={this.state.coordinates[0]} 61 waypoints={ 62 this.state.coordinates.length > 2 63 ? this.state.coordinates.slice(1, -1) 64 : undefined 65 } 66 destination={ 67 this.state.coordinates[this.state.coordinates.length - 1] 68 } 69 apikey={GOOGLE_MAPS_APIKEY} 70 strokeWidth={3} 71 strokeColor="hotpink" 72 optimizeWaypoints={true} 73 onStart={(params) => { 74 console.log( 75 `Started routing between "${params.origin}" and "${params.destination}"` 76 ); 77 }} 78 onReady={(result) => { 79 console.log(`Distance: ${result.distance} km`); 80 console.log(`Duration: ${result.duration} min.`); 81 82 this.mapView.fitToCoordinates(result.coordinates, { 83 edgePadding: { 84 right: width / 20, 85 bottom: height / 20, 86 left: width / 20, 87 top: height / 20, 88 }, 89 }); 90 }} 91 onError={(errorMessage) => { 92 // console.log('GOT AN ERROR'); 93 }} 94 /> 95 )} 96 </MapView> 97 ); 98 } 99} 100 101export default Example;
An example app can be found in a separate repo, located at https://github.com/bramus/react-native-maps-directions-example.
Please see CHANGELOG for more information on what has changed recently.
This code is inspired upon the article React Native Maps with Google Directions Api by Ali Oğuzhan Yıldız.
The MIT License (MIT). Please see License File for more information.
No vulnerabilities found.
No security vulnerabilities found.