How to compare and alter value for only one of them - javascript

I have got different markers .
For some of them, either the longitude or latitude is same .
In case for any of the markers if it has got same longitude or latitude, compared to other markers, I want to increase its latitude size .
But at the end I was ending up changing the coordinates for all the markers
Could you please let me know how to fix this ??
This is my fiddle
This is my code
function checkifgotsameLatitude(response , lator,lotor)
{
var a = 0;
for(var i=0;i<response.length;i++)
{
var latitusevalue = response[i].latitude;
var longitude = response[i].longititude;
if(latitusevalue==lator || lotor==longitude)
{
a++;
}
}
return a ;
}

This works if you want to offset one dealer from another if the difference is smaller than 0.0001 or similar
fiddle
function normaliseLat(num) {
var numDecimals = 4; // precision
return String(num.toFixed(numDecimals)).replace(".", "_");
}
function diffLng(lng, pos, response) {
return Math.abs(response[pos].longitude - lng)
}
var lats = [];
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longitude);
var norm = normaliseLat(lat);
var pos = lats.indexOf(norm);
if (pos!=-1) { // found
if (diffLng(lng,pos,response) < 0.0002) {
lat = parseFloat(lat)+0.00001;
}
}
lats[i]=norm;

I had a look at your fiddle and I think the solution is to compare item N with other items where the index is greater than N. You can do this by passing the starting index to your checkifgotsameLatitude function.
function checkifgotsameLatitude(response , lator,lotor, startIndex)
{
for(var i=startIndex;i<response.length;i++)
{
var latitusevalue = response[i].latitude;
var longitude = response[i].longititude;
if(latitusevalue==lator || lotor==longitude)
{
return true;
}
}
return false;
}
Updated fiddle
EDIT: the function can now return when the first match is found. this will speed things up. Updated fiddle

Something that doesn't appear to be accounted for is if after moving the marker, it then matches another marker. Or if you had more than two overlapping markers, all but one would just move to the same new location. I also changed the "or the same" to "and the same" as that part didn't make sense to me, assuming you are trying to adjust them so they don't overlap. But of course that could be changed back easily. I also changed the float equality to use a range.
I believe this corrects these issues:
Fiddle
while(checkifgotsameLatitude(response,lat,lng))
{
lat = lat+0.222;
response[i].latitude = lat;
}
function checkifgotsameLatitude(response , lator,lotor)
{
var a = 0;
for(var i=0;i<response.length;i++)
{
var latitusevalue = Math.abs(parseFloat(response[i].latitude) - lator) < 0.1;
var longitude = Math.abs(parseFloat(response[i].longititude) - lotor) < 0.1;
if(latitusevalue && longitude)
{
a++;
}
}
return a > 1;
}

Related

Store coordinates from prompt and calculate the distance

I work on distance calculation between coordinates and I built something which works fine.
var pointsCoordinates = [[5,7],[5,8],[2,8],[2,10]];
function lineDistance(points) {
var globalDistance = 0;
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}
console.log(lineDistance(pointsCoordinates));
I would like to improve it a little bit and send a prompt to store coordinates sent by users.
example:
alert(prompt("send me random coordinates in this format [,] and I will calculate the distance))
I would like to store theses coordinates and calculate the distance with my function which works.
I know I have to use push but it doesn't works, someone can help me to write it? I know it's simple but... I can't do it.
Thank you very much
Working and tested code. Take coordinates from the prompt and pass it to the lineDistance function and convert passed string into array.
function lineDistance(points) {
var globalDistance = 0;
var points = JSON.parse(points); // convert entered string to array
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}
var pointsCoordinates = prompt("send me random coordinates in this format [,] and I will calculate the distance");
if (coordinates != null)
console.log(lineDistance(coordinates)); //[[5,7],[5,8],[2,8],[2,10]]
else
alert("Entered value is null");
Hope this will help you.
var userPrompt = prompt("send me random coordinates");// e.g [100,2] [3,45] [51,6]
var pointsCoordinates = parseCoordinates(userPrompt);
function parseCoordinates(unparsedCoord) {
var arr = unparsedCoord.split(" ");
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i];
arr[i] = pair.substr(1, pair.length - 2).split(",")
}
return arr;
}
function lineDistance(points) {
var globalDistance = 0;
for(var i = 0; i < points.length - 1; i++) {
globalDistance += Math.sqrt(Math.pow(points[i + 1][0] - points[i][0], 2) + Math.pow(points[i+1][1]-points[i][1], 2));
}
return globalDistance;
}
console.log(pointsCoordinates);
console.log(lineDistance(pointsCoordinates));
If you use prompt you don't need to also wrap it with alert.
Also, prompt will return with a string value, so you'll need to parse the data you're getting back (unless you're fine with a string)
In this case, since you want to get back an array of points, parsing can be a more complicated than just converting values. My recommendation is to use JSON.parse() to parse the input array
In your case you could use this code
var coordString = prompt("send me random coordinates in this format [,] and I will calculate the distance");
try {
var coordinates = JSON.parse(coordString);
// now check that coordinates are an array
if ( coordinates.constructor === Array ) {
// this might still fail if the input array isn't made of numbers
// in case of error it will still be caught by catch
console.log(lineDistance(coordinates));
}
} catch(error) {
// if something goes wrong you get here
alert('An error occurred: ' + error);
}
I recommend reading the MDN docs for prompt() if you want to know what else you can do with them.
Also, the docs for JSON.parse() can be useful if you want to parse values from a text string.

Obtaining driving length between stops in ArcGIS

How can I obtain driving length between two stops in ArcGIS? I'm placing route from RouteTask service on a map and want to get lengths from that response too. I've thought about doing some iteration in DirectionsFeatureSet, but I already see that what I'm doing is complete nonsense.
var directions = solveResult[0].directions;
console.log(directions);
var length = 0;
var location = 0;
var obj = {};
$.each(directions.features, function (ind, val) {
var txt = val.attributes.text;
var indexOfLocation = txt.indexOf('Location');
if (indexOfLocation != -1) {
var digitTransform = txt.substring(indexOfLocation + 9);
var digit = "";
for (var i = 0; i < digitTransform.length; i++) {
var char = digitTransform[i];
if (isNumber(char)) {
digit += char;
} else break;
}
}
});
That's what I already did and that makes no sense.
In Google Maps API it's clear - every leg has it's own length. In ArcGIS responses I see no such easy approach.
The length is available as an attribute of each returned feature. So, given your directions variable, the following would give you the length of the first leg of the route:
directions.features[0].attributes.length

Measuring the length of an array, not characters in JavaScript

I have one problem regarding the length function. The problem is that when more than one entries come in the variable, it calculates the length perfectly but for a single entry, it starts to measure the number of characters instead of the amount of elements in the array. I want the alert to show 1 because there is one entry: finance consultant, but it's showing 18.
var win = Titanium.UI.createWindow({ backgroundColor:'#FFF' });
var tableView1=Titanium.UI.createTableView();
var Row = [];
Titanium.Yahoo.yql(
'select * from html where url="http://..." '
+ 'and xpath="//tbody/tr/td/a/font" limit 25',
function(e) {
results = e.data.font;
results = results.content;
alert(results.length);
for (var i = 0; i < results.length; i++) {
var rss = results[i];
var rssRow = Titanium.UI.createTableViewRow({ ... });
var titleLabel = Titanium.UI.createLabel({ ... });
rssRow.add(titleLabel);
Row.push(rssRow);
};
tableView1.setData(Row);
});
win.add(tableView1);
win.open();
You can try the following.
results = results.content;
if (typeof results === 'string')
results = [results];
alert(results.length);
So now you've forced a result that is a string to be an array of one string. The rest of your code should work unmodified.
In the line of slashingweapon answer, but simplified, why don't you just do this:
var length = 0;
if(typeof results === "string") {
length = 1;
} else {
length = results.length;
}
alert(length);
It's simpler and cleaner.

Sort computed areas

I have a google maps and I get all markers that are close a locaton (lat, lng).
This point is OK.
Now i want to sort theses markers, like in SQL we can do a "order by distance ASC" for example.
I saw in javascript have a method call sort() which can sort some numbers asc or desc for example.
markers have some informations: name, title, gender, city, postcode ...
my code:
var nbMeters = 50000;
for (var i = 0; i < markers.length; i++) {
var myMarker = markers[i];
coord2 = new google.maps.LatLng(myMarker.lat, myMarker.lng);
var distance = google.maps.geometry.spherical.computeDistanceBetween(coords, coords2);
if(distance <= nbMeters) {
alert(myMarker.name);
//OK my marker is close the variable coords, good !
//But how to know which marker is the closer, which is the second, the third ... and the less closer ??
}
}
Have you an idea?
Maybe try sth like this:
for (var i = 0; i < markers.length; i++) {
var myMarker = markers[i];
coord2 = new google.maps.LatLng(myMarker.lat, myMarker.lng);
var distance = google.maps.geometry.spherical.computeDistanceBetween(coords, coords2);
markers[i].distance = distance;
}
function sortMarkers(marker1, marker2) {
return marker1.distance - marker2.distance;
}
markers.sort(sortMarkers);
It's untested and based on http://www.w3schools.com/jsref/jsref_sort.asp

List Permutations

I'm trying to list all three letter permutations and this is the code I have -
window.permute = function(){
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var searchTerm ="aaa";
var position = 2;
changeString(searchTerm, position);
}
window.changeString = function(searchTerm, position){
if (position <0){
alert(newString);
return;
}
var alphabet = "abcdefghijklmnopqrstuvwxyz"
for (j=0; j < 26;j++){
var newString = searchTerm.substr(0, position) + alphabet[j] + searchTerm.substr(position+1);
var newPosition = position -1;
changeString(newString,newPosition);
}
return;
}
It's not working and I'm not sure why- can anyone help?
var permutate = (function() {
var results = [];
function doPermute(input, output, used, size, level) {
if (size == level) {
var word = output.join('');
results.push(word);
return;
}
level++;
for (var i = 0; i < input.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
output.push(input[i]);
doPermute(input, output, used, size, level);
used[i] = false;
output.pop();
}
}
return {
getPermutations: function(input, size) {
var chars = input.split('');
var output = [];
var used = new Array(chars.length);
doPermute(chars, output, used, size, 0);
return results;
}
}
})();
for more information, visit http://jinwolf.tumblr.com/post/26476479113/draw-something-cheat
for an working example, check this jsfiddle http://jsfiddle.net/jinwolf/Ek4N5/31/
alert(newString);
newString is not defined right there. Instead, you should use the argument passed:
alert(searchTerm);
Edit: I'm not entirely sure of your approach. It seems overly complicated. This seems to work. I understand that you rather have your own code working, but perhaps this helps you in solving. I don't quite get your substr part.
http://jsfiddle.net/NUG2A/2/
var alphabet = "abc"; // shortened to save time
function permute(text) {
if(text.length === 3) { // if length is 3, combination is valid; alert
console.log(text); // or alert
} else {
var newalphabet = alphabet.split("").filter(function(v) {
return text.indexOf(v) === -1;
}); // construct a new alphabet of characters that are not used yet
// because each letter may only occur once in each combination
for(var i = 0; i < newalphabet.length; i++) {
permute(text + newalphabet[i]); // call permute with current text + new
// letter from filtered alphabet
}
}
}
permute("");
This will result in the following being called:
permute("");
permute("a");
permute("ab");
permute("abc"); // alert
permute("ac");
permute("acb"); // alert
permute("b");
// ...
I'm not sure from your question that you mean "permutations" because usually permutations do not include repeated elements where it looks like you want to include "aaa".
Here are several algorithms for listing permutations you can go check out. If it turns out you mean to have repetitions, it looks like pimvdb has you covered.
Edit: So you know what you are getting into run-time wise:
With repetition (aaa,aab,...): n^k = 26^3 = 17,576
Without repetition (abc,bac,...): n!/(n-k)! = 26!/(26-3)! = 15,600
for (j=0; j < 26;j++){
should be
for (var j=0; j<26; j++) {
Without the declaration, j is a global variable, so it only takes one iteration to get to 26 and then all the loops terminate.
For permutations a recursive algorith as pimvd showed is always nice but don't forget you can just brute force it with for-loops when N is small:
for(int x1=0; x1 < 26; x1++)
for(int x2=0; x2 < 26; x2++)
for(int x3=0; x3 < 26; x3++){
//do something with x1, x2, x3
}
In C#:
void DoPermuation(string s)
{
var pool = new HashSet<string>();
//Permute("", , pool);
pool = Permute(new List<char>(s));
int i = 0;
foreach (var item in pool) Console.WriteLine("{0:D2}: {1}", ++i, item);
}
HashSet<string> Permute(List<char> range)
{
if (range.Count == 1) return new HashSet<string>(new string[] { range[0].ToString() });
var pool = new HashSet<string>();
foreach (var c in range)
{
var list = new List<char>(range);
list.Remove(c);
foreach (var item in Permute(list)) pool.Add(c + item);
}
return pool;
}

Categories