The shortest path between two addresses - javascript

Using google map, you can actually get the different possible routes between two addresses, also you get the length of every possible route.
I'm now working on a website with google map, i want to calculate the shortest path between two different addresses same as google map does. then get the path length back as javascript variable.

You can use these function:
google.maps.geometry.spherical.computeDistanceBetween (latLng1, latLng1);
The arguments are two LatLng objects.
Make sure you include:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>

I found it, it can be calculated using google map api called Distance Matrix it returns a json response containing The recommended path's length and Duration.
{
"destination_addresses" : [ "Témara, Maroc" ],
"origin_addresses" : [ "Rabat, Maroc" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "13,6 km",
"value" : 13620
},
"duration" : {
"text" : "23 minutes",
"value" : 1358
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
This should work fine:
function getDistance()
{
var url="http://maps.googleapis.com/maps/api/distancematrix/json?origins=rabat&destinations=temara&mode=driving&language=fr-FR&sensor=false";
var def = new jQuery.Deferred();
$.getJSON(url,function(json)
{
if (json.status=="OK")
{
var distance=json.rows[0].elements[0].distance.text;
}
def.resolve(distance);
});
return def.promise();
}
$.when(getDistance()).then(function(distance){
alert(distance);});
Demo

Related

Mongo not creating all docs in array and not giving errors

I have a long array of docs to create. When I create them I get no errors.
const docsJson =[some array of json of docs to create]
const orders = await MySchema.create(ordersJSON);
// orders.length returns the same number of docs as docsJson
But when I search for the new docs, only some were created.
const actualOrdersCreated = await MySchema.find({ _id: { $in: orders.map((p) => p._id) } });
// actualOrdersCreated.length returns less docs than in docsJson
What's causing this?
I think your data is to large.
The maximum BSON document size is 16 megabytes.
Reference: https://www.mongodb.com/docs/manual/reference/limits/
This was due to having a ttl (time to live) index on one mongo database and not the other. I was copying docs over from a database. The index on the first database was:
$ mongo "mongodb+srv://....database-1-url"
>> db.myschema.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"paidOn" : 1
},
"name" : "paidOn_1",
"background" : true
}
]
But the database I was working with had expireAfterSeconds.
$ mongo "mongodb+srv://....database-2-url"
>> db.myschema.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"expireAt" : 1
},
"name" : "expireAt_1",
"background" : true,
"expireAfterSeconds" : 86400
},
{
"v" : 2,
"key" : {
"paidOn" : 1
},
"name" : "paidOn_1",
"background" : true
}
]
So mongo was deleting the new docs where the expireAt field had an old date.
To fix it I ran await Order.syncIndexes(); in a script. This cleared the index to [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]. This is fine for my purpose. But the index isn't the same as the 1st database. The paidOn key is no longer indexes.
What I thought helped but didn't
At first I thought the issue was due to the large size of the jsonDocs.
I had objects with fields that had large base64 strings for images. These were placeholders, supposed to be replaced with http urls for the images.
After I removed the base64 strings I was able to upload the documents. I thought this helped but it was just speeding things up. It takes 1 minute for mongo to check up on expired docs.

extracting particular values from JSON

I am using Google Distance Matrix API and the response I got was in JSON:
{
"destination_addresses" : [ "Chandigarh, India" ],
"origin_addresses" : [ "Delhi, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "244 km",
"value" : 243506
},
"duration" : {
"text" : "3 hours 54 mins",
"value" : 14069
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I want to get the following values from JSON, destination_address, origin_address, distance, duration, and status. This is my code that I am trying out:
import requests as r
import json
a = r.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Delhi&destinations=Chandigarh&key=key")
#text form of a
tfa = a.text
print(tfa)
with open('data.json','w') as outfile:
json.dump(tfa,outfile)
json_data = json.loads(tfa)
print(json_data["destination_addresses"])
print(json_data["origin_addresses"])
print(json_data["rows"][0]["elements"][0]["distance"])
print(json_data["rows"]["elements"]["duration"])
The output that I am receiving gives me destination origin and distance, but I get an error when I try to grab duration, also the values inside the distance are printed as 'text':'244km','value':23432, but I only want to get the values not their labels. Is there any way to do that? Also is it possible to limit the values extracted inside the distance element (because I only want the text not the value)?
print(json_data["rows"][0]["elements"][0]["distance"]["value"])
Adding ["value"] to your current code will only show the value.
print(json_data["rows"]["elements"]["duration"])
You try to get something from the same level as the distance but you forget the [0] in this line. You can basically copy and paste the code that prints the distance value but replace distance by duration:
print(json_data["rows"][0]["elements"][0]["duration"]["value"])

Store ajax response object in global variable --- Fields get missing

I'm implementing an asynchronous webpage in Grails where I make a call to a controller and render the response as a D3.js network. I stored the object into a global variable for further use. The function worked fine when data is returned. However when I tried to use the object later I found some fields became undefined.
var similar;
function asynchroNetwork() {
var jsonData = $.ajax({
url: "${createLink(controller:'environment', action:'asynchro')}",
dataType: "json",
async: true
}).done(function(jsonData) {
console.log(jsonData);
//console.log(jsonText);
document.getElementById("result").innerHTML="Done";
console.log(jsonData.all);
//set global variable
similar=jsonData;
console.log("The object got");
console.log(similar);
draw();
});;
}
function draw(){
console.log(similar);
//draw the network based on object
}
The controller returns the following JSON:
{
"\u521B\u4E1A" : {
"nodes" : [{
"group" : 1,
"name" : "\u6c88\u9633\u8f9b\u98962\u4e16"
}
],
"links" : []
},
"all" : {
"nodes" : [{
"group" : 1,
"name" : "qwe25322570"
}, {
"group" : 1,
"name" : "\u660e\u5fb7\u7b03\u884c"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u53ef\u4e50"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u5f6d\u79c0\u8363"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u738b\u632f\u534e"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u8f9b\u98962\u4e16"
}
],
"links" : [{
"value" : 1.0,
"target" : "\u6c88\u9633\u8f9b\u98962\u4e16",
"source" : "\u660e\u5fb7\u7b03\u884c"
}, {
"value" : 1.0,
"target" : "\u6c88\u9633\u8f9b\u98962\u4e16",
"source" : "qwe25322570"
}
]
}
}
In the draw() function it uses similar[all] to draw a graph. But in the links field I see the fields source and target are all undefined, while all fields in the nodes are all fine.
I don't think the encoding is the cause because nodes also contains UTF8 characters in the fields but none got missing. After the object is passed back from asychronous function the object similar is okay, but the next time draw() is called, I can see the field links go undefined.
Does anyone know what could be the cause of this problem? I guess it maybe related to nested fields.
Did you try passing your data as an argument to the draw function? If not, then:
In your ajax callback:
similar = jsonData;
draw(similar) //pass the json
draw function:
function draw(json) {
console.log(json);
}

Using JSON how to assign multiple images or a better way of doing it suggested?

At the moment I'm using JSON to call words for my games I'm making but I wondering if I could do it with multiple images without a massive length of code for each round. Here is what I got so far but it's complaining about the duplicate "url". Or would I be better of using an array
Thanks
{
"images": [
{"imageID" : "game1", "url" : "gameImages/img1.jpg", "url" : "gameImages/img2.jpg",
"url" : "gameImages/img3.jpg", "url" : "gameImages/img4.jpg" }
{"imageID" : "game2", "url" : "gameImages/img5.jpg", "url" : "gameImages/img6.jpg",
"url" : "gameImages/img7.jpg", "url" : "gameImages/img8.jpg" }
]
}
Since it appears you're aware of the use of arrays in JSON already (you have two entries within your images array already), how about storing each set of urls in an array:
{
"images": [
{
"imageID": "game1",
"urls": [
"gameImages/img1.jpg",
"gameImages/img2.jpg",
"gameImages/img3.jpg",
"gameImages/img4.jpg"
]
},
{
"imageID": "game2",
"urls": [
"gameImages/img5.jpg",
"gameImages/img6.jpg",
"gameImages/img7.jpg",
"gameImages/img8.jpg"
]
}
]
}

manage neo4j cross relationship in d3.js

I start recently to work with Neo4j database and i'm trying to display a graph using d3js (i'm new with it too!).
For my test i used the movie example data include in neo4j.
Using JQuery ajax and neo4j REST API, i find a way to make it more or less work.
But currently i can't make an actor link to several movie (or i duplicate them!).
here is currently my Cypher request:
match (a)-[r]->(m) RETURN {id: id(m), name: m.title}, collect({name : a.name, id: id(a)})
and the answer i get look like this:
{
"columns" : [ "{id: id(m), name: m.title}", "collect({name : a.name, id: id(a)})" ],
"data" :
[
[
{ "id" : 3, "name" : "The Matrix Reloaded" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
],
[
{ "id" : 4, "name" : "The Matrix Revolutions" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
],
[
{ "id" : 2, "name" : "The Matrix" },
[
{ "id" : 5, "name" : "Keanu Reeves" },
{ "id" : 6, "name" : "Laurence Fishburne" },
{ "id" : 7, "name" : "Carrie-Anne Moss" }
]
]
]
}
So i'm thinking of 2 workarounds : either i find a way in d3 to do it (but i have a real hard time to understand d3js for this) or i change my cypher request to get the relationship in a different way.
i can of course make a huge workaround in javascript but my objective is to keep the code as much effective as possible (at the end i want to use it to get a lot of data).
i use the example here : http://bl.ocks.org/mbostock/1093130
where i modify the flatten function like this (and some other minor change) :
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
root.data.forEach(function(l) {
var childrenlist = [];
l[1].forEach(function(actor) {
var ac = { name: actor.name, id: actor.id };
childrenlist.push(ac);
nodes.push(ac);
});
var movie = { id: l[0].id, name: l[0].name, children: childrenlist };
nodes.push(movie);
});
return nodes;
}
/*! end of flatten */
So ! since i have a hard time with d3js, i'm looking a way to make my cypher request to give me the relationship info in a different way. more like this example : http://bl.ocks.org/mbostock/4062045
i'm really stuck because i don't know how to build my cypher request!
i'm looking for a way to get the relationship source and destination node id and the node list but i don't know how to do both!
i want to mix this 2 requests:
match (a)-[r]->(m) RETURN {id: id(m), name: m.title}}
and something like this (but i don't know how to get relationship source and dest):
match (a)-[r]->(m) RETURN {src: id(r.src), dst: id(r.dst)}
if you could help me it would be awesome ! i hope i'm clear enough.
of course i'm open to any other suggestions or leads!
Thanks in advance!

Categories

Resources