How to Display a Route Between Two Geocoords in Google Maps

How to display a route between two geocoords in google maps?

this is working example link. check it out. it helps to create the route overlay on the map. here is the complete source code for that.

How to display a path between two points in android google maps activity?

Here is the way to draw a path.

here is the link for the library - https://github.com/ar-android/DrawRouteMaps

Add that library into your Android project.

Apply the following code inside onMapReady Method

Android Code:

    @Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

//Pass the origin coordinates(latitude,longitude)
LatLng origin = new LatLng(-7.788969, 110.338382);

//Pass the destination coordinates(latitude,longitude)
LatLng destination = new LatLng(-7.781200, 110.349709);

DrawRouteMaps.getInstance(this)
.draw(origin, destination, mMap);
DrawMarker.getInstance(this).draw(mMap, origin, R.drawable.marker_a, "Origin Location");
DrawMarker.getInstance(this).draw(mMap, destination, R.drawable.marker_b, "Destination Location");

LatLngBounds bounds = new LatLngBounds.Builder()
.include(origin)
.include(destination).build();
Point displaySize = new Point();
getWindowManager().getDefaultDisplay().getSize(displaySize);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, displaySize.x, 250, 30));
}

You can also change the route color by applying this code inside colors.xml :

   <color name="colorRouteLine">YOUR COLOUR CODE</color>

embed google map with a route between two marks using latitude and longitude

Use the Embed API

from the documentation

https://www.google.com/maps/embed/v1/directions

?key=YOUR_API_KEY

&origin=Oslo+Norway

&destination=Telemark+Norway

&avoid=tolls|highways

The following URL parameters are required:

origin defines the starting point from which to display directions. The value can be either a place name, address or place ID. The string should be URL-escaped, so an address such as "City Hall, New York, NY" should be converted to City+Hall,New+York,NY. (The Google Maps Embed API supports both + and %20 when escaping spaces.) Place IDs should be prefixed with place_id:.
destination defines the end point of the directions.

example:

origin=40.7127837,-74.0059413  (New York, NY)
destination=42.3600825,-71.05888 (Boston, MA)

iframe code:
<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/directions?origin=40.7127837,-74.0059413&destination=42.3600825,-71.05888&key=..." allowfullscreen></iframe>

working example

How to display google map directions given latitude and longitude information in r

This basically comes down to creating a route_df and then plotting the results as geom_path. For example, for a single route, you could do something like this:

library(ggmap)

route_df <- route(from = "Hyderabad, Telangana 500085, India",
to = "Kukatpally, Hyderabad, Telangana 500072, India",
structure = "route")

my_map <- get_map("Hyderabad, Telangana 500085, India", zoom = 13)

ggmap(my_map) +
geom_path(aes(x = lon, y = lat), color = "red", size = 1.5,
data = route_df, lineend = "round")

Map with route

So you could probably approach this by generating each of the from-to routes and rbind-ing all of the results into one large route_df and plotting the final results. It's easier for others to help you if you make an attempt and show where (with code) you are getting stuck. You may want to edit your original question or possibly submit a new one after you show what you have tried.

This SO post with this answer should prove helpful.

Draw a path between two points on google maps

You want to parse json from here https://maps.googleapis.com/maps/api/directions/json?origin=50,8&destination=51,8&sensor=false&mode=driving

You need this nested structure. Some tips by me: read some tutorials what json is and how does it work in Swift. You find a lot in web. Alternativ take a pod (library) like ObjectMapper or SwiftyJson.

 if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{

// print("json \(json)")
if let routes = json["routes"] as? [Any] {

if let route = routes[0] as? [String:Any] {

if let legs = route["legs"] as? [Any] {

if let leg = legs[0] as? [String:Any] {

if let steps = leg["steps"] as? [Any] {

if let step = steps[0] as? [String:Any] {

if let polyline = step["polyline"] as? [String:Any] {

if let points = polyline["points"] as? String {
print("points \(points)")
}
}
}
}
}
}
}
}
}

How should we show path between two latitudes & longitudes in google maps using Swift

Try this

let origin = "\(12.9077869892472),\(77.5870421156287)"
let destination = "\(12.907809),\(77.587066)"
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)")
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
if json["status"] as! String == "OK"
{
let routes = json["routes"] as! [[String:AnyObject]]
OperationQueue.main.addOperation({
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"] as! [String:String]
let points = routeOverviewPolyline["points"]
let path = GMSPath.init(fromEncodedPath: points!)
let polyline = GMSPolyline(path: path)
polyline.strokeColor = .blue
polyline.strokeWidth = 4.0
polyline.map = mapViewX//Your GMSMapview
}
})
}
}catch let error as NSError{
print(error)
}
}
}).resume()

How to draw line between two points in JavaScript - Google Maps Api Route

You can use the Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer, which can automatically handle the display in the map.

Here is the code I made which handles the use-case (Geolocating Point A, Draggable Marker B, then having a route between 2 points) from your description. You can also check it here.
Hope this helps!

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
#map {
height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>

<body>
<div id="map"></div>
<script>
var map, infoWindow, markerA, markerB, drag_pos;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
markerA = new google.maps.Marker({
map: map
});
markerB = new google.maps.Marker({
map: map
});
infoWindow = new google.maps.InfoWindow;
var directionsService = new google.maps.DirectionsService();
var directionsRenderer1 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
var directionsRenderer2 = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
polylineOptions: {
strokeColor: "gray"
}
});

// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};

map.setCenter(pos);
map.setZoom(15);
//Put markers on the place
infoWindow.setContent('Your Location');
markerA.setPosition(pos);
markerA.setVisible(true);
markerA.setLabel('A');
markerA.addListener('click', function() {
infoWindow.open(map, markerA);
});

//Get new lat long to put marker B 500m above Marker A
var earth = 6378.137, //radius of the earth in kilometer
pi = Math.PI,
m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree

var new_latitude = pos.lat + (500 * m);
var new_pos = {
lat: new_latitude,
lng: position.coords.longitude
};

markerB.setPosition(new_pos, );
markerB.setVisible(true);
markerB.setLabel('B');
markerB.setDraggable(true);

//Everytime MarkerB is drag Directions Service is use to get all the route
google.maps.event.addListener(markerB, 'dragend', function(evt) {
var drag_pos1 = {
lat: evt.latLng.lat(),
lng: evt.latLng.lng()
};

directionsService.route({
origin: pos,
destination: drag_pos1,
travelMode: 'DRIVING',
provideRouteAlternatives: true
},
function(response, status) {
if (status === 'OK') {

for (var i = 0, len = response.routes.length; i < len; i++) {
if (i === 0) {
directionsRenderer1.setDirections(response);
directionsRenderer1.setRouteIndex(i);

} else {

directionsRenderer2.setDirections(response);
directionsRenderer2.setRouteIndex(i);
}
}
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>

</html>


Related Topics



Leave a reply



Submit