I put all the encoded_lat_lng values for each step of a leg into an array using jQuery.
var leg_array = {};
var enc_array = [];
for(var c = 0; c < result.routes[0].legs.length;c++) {
for (var b =0; b < result.routes[0].legs[c].steps.length; b++){
var lat_lngs = result.routes[0].legs[c].steps[b].encoded_lat_lngs;
leg_array[c]={};
enc_array[b]=lat_lngs;
leg_array[c]=enc_array;
}
}
var legs_polyline = JSON.stringify(leg_array);
Individually they display a polyline but i want to merge each polyline. I want to get a polyline for each leg of a route.
For example polyline number 1 is m}zxHikCC?G#G?MDEBE#SHWRIFEFGHEFMTEJCFGRKTEJEJGLEJEHGHCDEFOLEDGDE#GBEBG#IBO#OBW#I?G#GAK?MCQCwBg#[M[GSEMAO?c##Y#qBNO?y##sFCk#I[?[?c#?_#?KAe##aA?M?qA?Y?]#s#La#PmEnAWHq#^k#f#s#h#_A|#w#n#o#j#[ZcAfAQPIHKJq#p#m#j#c#b#aAv#A?a#RWL_#Jc#Hi#PwBt#iEBaBt#y#b#kCB_#TKFaB|#a#NG#_#H[BaB#g##y#BA?_#Ls#^mAx#qElBA#y#Z
polyine number 2 is k_yHcuAD^Fx#?#BhAJhEHEJfE#l#JD#r#FhD#PD~C#~#?H?v#?X?R#P?H#H#LDNBJBJJXLTRzC
How do i merge them so i can view a static map http://maps.google.com/maps/api/staticmap?size=500x300&sensor=false&path=enc:$polyline
This example only shows two polyline numbers, the amount might excede 2000 characters.
You need to decode the encoded polylines (to latitude/longitude coordinates), then re-encode the new polyline.
encoding algorithm
Related
Need some help with google maps polygon areas. I have a many markers plotted across the google map. Have some polygon areas plotted on map too. I want to find the total of marker points covered by a polygon, whenever the polygon area is clicked. Kindly guide or provide some good links in this direction
Thanks.
You could try ray casting algorithm. The implementation would be something like this:
var markers = []; // list of your markers
var polygonPath = polygon.getPath();
var location;
for (var i = 0; i < markers.length; i++) {
location = markers[i].getPosition();
console.log(isPositionInside(location.lat, location.lng, polygonPath));
}
function isPositionInside(mLat, mLng, polygonPoints) {
var isInside = false;
for (var a = 0, b = polygonPoints.length - 1; a < polygonPoints.length; b = a++) {
var aLng = polygonPoints[a].lng,
aLat = polygonPoints[a].lat,
bLng = polygonPoints[b].lng,
bLat = polygonPoints[b].lat;
if ((aLng > mLng) != (bLng > mLng) && (mLat < (bLat - aLat) * (mLng - aLng) / (bLng - aLng) + aLat)) {
isInside = !isInside;
}
}
return isInside;
};
This isn't the most optimal solution, as you can read in the wiki article, but in most cases it will get the job done.
I know how to find near by locations from MySQL database using Round circle radius query and I have given answer of the same on another SO question as well here.
But I wish to do some different thing from this now. Here what happened is the query returns the result from center of the point which includes entire circle of radius. I wish to get points only of the half circle. I know this is possible and its all mathematical calculation and I am little weak in it that's why asking for experts help.
See this image, it will give very clear idea.
As you can see in the image only front part location is needed, not the back side part. Need to ignore the back side part. Also I have divided the radius in different color to make them appear as zones - like red is zone1, orange is zone 2 and yellow is zone 3. This are virtual zones to filter the data (locations).
All suggestions are welcome.
You can plot points inside a segment using Haversine/Spherical Law of Cosines for the radius. Then use pointInPolygon() to find only those within segment. You will also require function to create polygon.
polySides = number of sides in polygon
pointLatArr = Lat of point in in polygon array
pointLngArr = Lng of point in in polygon array
dat.lat = Lat from Haversine results
dat.lng = Lng from Haversine results
if (pointInPolygonpolySides,pointLatArr,pointLngArr,dat.lat,dat.lng)){
var latlng = new google.maps.LatLng(dat.lat,dat.lng);
addMarker(latlng,dat.name);
bounds.extend(latlng);
}
function pointInPolygon(polySides,polyX,polyY,x,y) {
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyY[i]<y && polyY[j]>=y || polyY[j]<y && polyY[i]>=y) {
if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
oddNodes=!oddNodes;
}
}
j=i; }
return oddNodes;
}
Function for segment polygon
function drawSegment(start,end,radius) {
var d2r = Math.PI / 180;
pointLatArr = new Array();
pointLngArr = new Array();
polyLatLngs = new Array(); // latLngs of polygon
var polyLat = (radius /3963.189) / d2r; // miles
var polyLng = polyLat / Math.cos(center.lat() * d2r);
var centerLatLng = new google.maps.LatLng(center.lat(),center.lng());//Center to start
pointLatArr.push(center.lat());
pointLngArr.push(center.lng());
polyLatLngs.push(centerLatLng);
bounds.extend(centerLatLng);
// Create polygon points (extra point to close polygon)
for (var i = start; i < end; i++) {
// Convert degrees to radians
var theta = i * d2r;
var pointLat = center.lat() + (polyLat * Math.sin(theta));
var pointLng = center.lng() + (polyLng * Math.cos(theta));
var pointLatLng = new google.maps.LatLng(
parseFloat(pointLat), parseFloat(pointLng));
polyLatLngs.push(pointLatLng);
pointLatArr.push(pointLat);
pointLngArr.push(pointLng);
bounds.extend(pointLatLng);
}
var centerLatLng = new google.maps.LatLng(center.lat(),center.lng());//End to center
polyLatLngs.push(centerLatLng);
pointLatArr.push(center.lat());
pointLngArr.push(center.lng());
polySides = polyLatLngs.length;
Map using this technique
}
See Demo
I am trying to figure out a way to show items using the map script with the following info:
10 miles north running along US 1 plot a marker 10 feet to the right(east) of US 1. And to set for example that mile 0 starts at the intersection between US 1 and Main Street.
Perhaps someone has run into this before or something similar and will be kind enough to give me some pointers.
Thanks!
Following Eric's tip I was able to create a function to grab a polyline for the road centerline from Google Maps. Then use the google api service to convert that polyline into latitude and longitude coordinates. From then on, it was all spherical geometry coding. Below is my humble little code:
//Function to grab a centerline from the Map Api
//start = lat and long for beginning of roadway centerline ie [27.64681, -82.38438]
//end = lat and long for end of roadway centerline ie [27.71248, -82.33518]
//startmile = beginning milepost
function grabmap(start, end, startmile){
startmile = parseFloat(startmile);
var points = [];
var plinex = [];
var pliney = [];
var directions = Maps.newDirectionFinder().setOrigin(start).setDestination(end).getDirections();
// Much of this code is based on the template referenced in
// http://googleappsdeveloper.blogspot.com/2010/06/automatically-generate-maps-and.html
for (var i in directions.routes) {
for (var j in directions.routes[i].legs) {
for (var k in directions.routes[i].legs[j].steps) {
// Parse out the current step in the directions
var step = directions.routes[i].legs[j].steps[k];
// Call Maps.decodePolyline() to decode the polyline for
// this step into an array of latitudes and longitudes
var path = Maps.decodePolyline(step.polyline.points);
points = points.concat(path);
}
}
}
var lengthvector = (points.length / 2);
for ( i = 0; i <= points.length; i++){
if ( i % 2 == 0){
plinex = plinex.concat(points[i]);
pliney = pliney.concat(points[(i+1)]);
}
}
var plineVector = new Array(plinex.length - 2);
for ( i = 0; i <= plinex.length - 2; i++){
plineVector[i] = new Array(2);
plineVector[i][0] = plinex[i];
plineVector[i][1] = pliney[i];
}
return plineVector;
}
I haven't used the Maps Service extensively, but it should be possible. You use the DiretionFinder to get the latitudes and longitudes of points along the path, and then do some math to get the offset for the marker.
I am having a map with some polylines with the distance [api v3]. I want that when someone drag the polyline at the same time the distance also get updated but dont know how to do. Please help me, any good tutorial or another threads are most welcome
Thanks for helping me
Naveen
This page describes using draggable markers and updating the distance when a marker is moved.
http://exploregooglemaps.blogspot.com.br/2012/02/measuring-distance-with-markers.html
There is a attribute which makes your polyline editable.
polyPath.setEditable(true);
Now use a listener to check the editing.
google.maps.event.addListener(polyPath, 'capturing_changed', function() {
var array = polyPath.getPath(); //getPath() gives u array of current markers latlng over map
var tempDistance = 0;
var tempPathArray = [];
for(i = 0; i < array.length; i++){
tempPathArray.push(array.getAt(i));
}
for(k = 1; k < tempPathArray.length; k++)
{
var calculateNewDistance=google.maps.geometry.spherical.computeDistanceBetween(tempPathArray[k-1],tempPathArray[k]);
tempDistance += calculateNewDistance;
}
}
// make sure to add the following script to compute the distance between two latlngs
I have a google maps app which plots markers as it loads. One of the new requirment is to to add a Polygon overlay encompassing a selection of markers by the user. I was able to achieve that using the Geometry Controls of the GMaps Utility Library
Now, the next step is to form a group of the selected markers for which I would need to determine if the lat lngs of the markers falls within the lat lngs of the polygon? Is there a way to determine the lat lngs of a polygon and compute if the marker's lat lng is within its boundaries?
I have never directly messed around with Google Maps, but you can store the points that make up the polygon and then use the Point-In-polygon Algorithm to check if a given longitude and latitude point is within a polygon or not.
// Create polygon method for collision detection
GPolygon.prototype.containsLatLng = function(latLng) {
// Do simple calculation so we don't do more CPU-intensive calcs for obvious misses
var bounds = this.getBounds();
if(!bounds.containsLatLng(latLng)) {
return false;
}
// Point in polygon algorithm found at http://msdn.microsoft.com/en-us/library/cc451895.aspx
var numPoints = this.getVertexCount();
var inPoly = false;
var i;
var j = numPoints-1;
for(var i=0; i < numPoints; i++) {
var vertex1 = this.getVertex(i);
var vertex2 = this.getVertex(j);
if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
inPoly = !inPoly;
}
}
j = i;
}
return inPoly;
};
Following npinti's suggestion, you may want to check out the following point-in-polygon implementation for Google Maps:
Check if a polygon contains a coordinate in Google Maps
This has been updated in v3. You can do this calculation via the google.maps.geometry.poly namespace API Documentation