Google Maps determine distance along Line - google-maps

I am trying to determine the distance of a point along a given Polyline (from the start point) in Google maps (given that the user clicks on the Polyline and I get the point coordinates in the event).
So far, this is the only thing that comes to mind:
Iterate over all segments in the Polyline until I find one such that
d(line, point) ~= 0, keeping track of the distance covered so far.
Interpolate on the segment the point is on to find its distance
relative to the start of the segment.
Sadly, this seems rather complicated for something that should be straightforward to do.
Is there any easier way?
P.S.: I'm using API v3

So, after much searching I decided to implement the algorithm as described above. Turned out it isn't as bad as I thought. Should anyone ever land on this page, the full code is below:
var DistanceFromStart = function (/*latlng*/ markerPosition) {
var path = this.polyline.getPath();
var minValue = Infinity;
var minIndex = 0;
var x = markerPosition.lat();
var y = markerPosition.lng();
for (var i = 0; i < path.getLength() - 1; i++) {
var x1 = path.getAt(i).lat();
var y1 = path.getAt(i).lng();
var x2 = path.getAt(i + 1).lat();
var y2 = path.getAt(i + 1).lng();
var dist = pDistance(x, y, x1, y1, x2, y2);
if (dist < minValue) {
minIndex = i;
minValue = dist;
}
}
var gdist = google.maps.geometry.spherical.computeDistanceBetween;
var dinit = gdist(markerPosition, path.getAt(minIndex));
var dtotal = gdist(path.getAt(minIndex), path.getAt(minIndex + 1));
var distanceFromStart = 0;
for (var i = 0; i <= minIndex - 1; i++) {
distanceFromStart += gdist(path.getAt(i), path.getAt(i + 1));
}
distanceFromStart += dtotal * dinit / dtotal;
return distanceFromStart;
}
function pDistance(x, y, x1, y1, x2, y2) {
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = dot / len_sq;
var xx, yy;
if (param < 0 || (x1 == x2 && y1 == y2)) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
return Math.sqrt(dx * dx + dy * dy);
}
If you see anything to improve, do let me know.

If you get the coordinates for the start and end points, then use the haversine algorithm to calculate the distance you can easily find the distance between two points taking into consideration the curvature of the earth.
Here is the formula (you may need to convert in into the language you are using):
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
variable d is your distance.
Hope this helps

Related

Canvas quadraticCurve center point

I want need to know how detect center coordinates of quadraticCurve in HTML5 canvas. I want to draw arrow in this center point of curve.
There is my draw curve method:
function draw_curve(Ax, Ay, Bx, By, M, context) {
var dx = Bx - Ax,
dy = By - Ay,
dr = Math.sqrt(dx * dx + dy * dy);
// side is either 1 or -1 depending on which side you want the curve to be on.
// Find midpoint J
var Jx = Ax + (Bx - Ax) / 2
var Jy = Ay + (By - Ay) / 2
// We need a and b to find theta, and we need to know the sign of each to make sure that the orientation is correct.
var a = Bx - Ax
var asign = (a < 0 ? -1 : 1)
var b = By - Ay
var bsign = (b < 0 ? -1 : 1)
var theta = Math.atan(b / a)
// Find the point that's perpendicular to J on side
var costheta = asign * Math.cos(theta)
var sintheta = asign * Math.sin(theta)
// Find c and d
var c = M * sintheta
var d = M * costheta
// Use c and d to find Kx and Ky
var Kx = Jx - c
var Ky = Jy + d
// context.bezierCurveTo(Kx, Ky,Bx,By, Ax, Ax);
context.quadraticCurveTo(Kx, Ky, Bx, By);
// draw the ending arrowhead
var endRadians = Math.atan((dx) / (dy));
context.stroke();
var t = 0.5; // given example value
var xx = (1 - t) * (1 - t) * Ax + 2 * (1 - t) * t * Kx + t * t * Bx;
var yy = (1 - t) * (1 - t) * Ay + 2 * (1 - t) * t * Ky + t * t * By;
var k = {};
k.x = xx;
k.y = yy;
SOLVED BY THIS CODE, T is parameter which set position on the curve:
var t = 0.5; // given example value
var xx = (1 - t) * (1 - t) * Ax + 2 * (1 - t) * t * Kx + t * t * Bx;
var yy = (1 - t) * (1 - t) * Ay + 2 * (1 - t) * t * Ky + t * t * By;
var k = {};
k.x = xx;
k.y = yy;

Is there a way to rotate the object and then calculate its x and y coordinates as if it was turned around some point without measurement accuracy?

Is there a way to rotate the object with the property rotation, and then calculate its x and y coordinates as if it was turned around some point
without measurement accuracy?
public static function pointRotate (object:DisplayObject, center:Point,angle:Number) : void
{
var r:Number = angle * Math.PI / 180;
var s:Number = Math.sin(r);
var c:Number = Math.cos(r);
var dX:Number = object.x - center.x;
var dY:Number = object.y - center.y;
object.rotation += angle;
object.x = center.x + dX * c - dY * s;
object.y = center.y + dX * s + dY * c;
}
package
{
import flash.geom.Point;
import flash.display.DisplayObject;
public function pointRotate(object:DisplayObject, center:Point, angle:Number) : void
{
// return to zero
angle += object.rotation;
var a0:Number = - object.rotation * Math.PI / 180;
var s0:Number = Math.sin(a0);
var c0:Number = Math.cos(a0);
var dX0:Number = object.x - center.x;
var dY0:Number = object.y - center.y;
object.rotation = 0;
object.x = Math.round(center.x + dX0 * c0 - dY0 * s0);
object.y = Math.round(center.y + dX0 * s0 + dY0 * c0);
// new rotation
var r:Number = angle * Math.PI / 180;
var s:Number = Math.sin(r);
var c:Number = Math.cos(r);
var dX:Number = object.x - center.x;
var dY:Number = object.y - center.y;
object.rotation += angle;
object.x = center.x + dX * c - dY * s;
object.y = center.y + dX * s + dY * c;
}
}

Building circle meter gauge

I was wondering if someone could help me with a circle meter gauage i have taken some code from a different example and i am just protypting stuff to see if i can get it to work here is a working example.
http://jsbin.com/ixuyid/28/edit
Click run with javascript
Code below
var context;
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
//use a reusable function
function drawCircle(num){
console.log(num);
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 0 * Math.PI;
var endAngle = num * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 5;
// line color
context.strokeStyle = 'black';
context.stroke();
}
drawCircle();
var num = 1;
setInterval(function(){
},1000);
+function(){
var ctx = new webkitAudioContext()
, url = '//kevincennis.com/sound/loudpipes.mp3'
, audio = new Audio(url)
// 2048 sample buffer, 1 channel in, 1 channel out
, processor = ctx.createJavaScriptNode(2048, 1, 1)
, meter = document.getElementById('meter')
, source
audio.addEventListener('canplaythrough', function(){
source = ctx.createMediaElementSource(audio)
source.connect(processor)
source.connect(ctx.destination)
processor.connect(ctx.destination)
audio.play()
}, false);
// loop through PCM data and calculate average
// volume for a given 2048 sample buffer
processor.onaudioprocess = function(evt){
var input = evt.inputBuffer.getChannelData(0)
, len = input.length
, total = i = 0
, rms
while ( i < len ) total += Math.abs( input[i++] )
rms = Math.sqrt( total / len )
meter.style.width = ( rms * 100 ) + '%';
context.clearRect(100,50,200,200);
drawCircle(rms);
}
}()
I seem to be having issue with the levels???
Any help
Change these two lines in the drawCircle function:
var startAngle = 0; //multiplying with 0 will result in 0
var endAngle = 360 * num * Math.PI / 180;
Your num seem to be a value between 0 and 1 so we need to add what we're using that with, here 360 degrees, then convert by using PI / 180.
The other problem is that the clearRect wasn't extended far enough so it left part of the arc uncleared to the right.
Tip: To make it look more realistic you can update your rms only when the new rms is higher, and if not just subtract a small value for each frame.
For example:
//global scope
var oldRMS = 0;
Inside your processor.onaudioprocess after vars:
if (rms > oldRMS) oldRMS = rms;
meter.style.width = ( oldRMS * 100 ) + '%';
context.clearRect(100,50,canvas.width,canvas.height);
drawCircle(oldRMS);
oldRMS -= 0.04; //speed of fallback
Modifcations:
http://jsbin.com/ixuyid/29/edit

Laplace image filter

I took the example of Laplace from "Making image filters with Canvas", but I can not understand the use of Math.min() function in the following lines. Can anyone explain to me how the Laplace?
var weights = [-1,-1,-1,
-1, 8,-1,
-1,-1,-1];
var opaque = true;
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var imgd = context.getImageData(0, 0, canvas.width, canvas.height);
var src = imgd.data;
var sw = canvas.width;
var sh = canvas.height;
var w = sw;
var h = sh;
var output = contextNew.createImageData(w, h);
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = Math.min(sh-1, Math.max(0, sy + cy - halfSide));
var scx = Math.min(sw-1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
its algorithm is something like
for y = 0 to imageHeight
for x = 0 to imageWidth
sum = 0
for i = -h to h
for j = -w to w
sum = sum + k(j, i) * f(x – j, y – i)
end for j
end for i
g(x, y) = sum end for x end for y

Advanced coordinate rotation

package {
import flash.display.Sprite;
import flash.geom.Point;
import flash.events.Event;
public class Game2 extends Sprite {
var balls:Array;
var radius:Number = 50;
var centerX:Number = stage.stageWidth / 2;
var centerY:Number = stage.stageHeight / 2;
var i:int = 0;
var angle:Number = 0.1;
var sin:Number = Math.sin(angle);
var cos:Number = Math.cos(angle);
public function Game2() {
init();
}
function init():void
{
balls = new Array();
for(i = 0; i < 8; i++)
{
var ball:Ball = new Ball(10, 0x00FF00);
var xposition = centerX + Math.cos(i / 8 * Math.PI * 2) * radius;
var yposition = centerY + Math.sin(i / 8 * Math.PI * 2) * radius;
ball.x = xposition;
ball.y = yposition;
addChild(ball);
balls.push(ball);
}
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onEnterFrame(e:Event):void
{
for(i = 0; i < balls.length; i++)
{
var ball:Ball = balls[i];
var x1:Number = ball.x - stage.stageWidth / 2;
var y1:Number = ball.y - stage.stageHeight / 2;
var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;
ball.x = stage.stageWidth / 2 + x2;
ball.y = stage.stageHeight / 2 + y2;
}
}
}
}
Can someone explain the work of this formula?:
var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;
i just can't figure it out, if we edit it like this:
var x2:Number = x1 - y1;
var y2:Number = x1 + y1;
all the balls are moving so fast and get out of screen bounds, and also why if we change it like this:
var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;
or
var x2:Number = cos * x1 - sin * y1;
var y2:Number = cos * y1 + sin * x1;
it will work equal, as far as i understanded is that here happens some kind of simetry, if we are on the left or right sides the velocity x == 0 and y is at the maximum velocity of its position the y slows down each time he get closer to the top or bottom, if we are on the top or bottom the velocity y == 0 and x is at maximum speed of his position then also slows down each time he gets closer to the right or left sides, i traced it, but i can't understand why we have to multiply it by cos and sin, i've traced this moments but still can't figure it out, can anyone explain this moment?
The two formulas represent a rotation matrix multiplied with a vector.