How to pass json data from the controller to javascript - javascript

In my cluster Table have cluster coordinates column name description,
i am directly storing coordinates in Json format like below is my cluster table ,using these coordinates i want to draw multiple cluster(polygons)
in google map,
id | description
----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 | {"points":[{"lat":14.232437996569354,"lng":76.409912109375},{"lat":13.336175186494927,"lng":77.1185302734375},{"lat":12.961735843534294,"lng":77.596435546875},{"lat":12.511665400971031,"lng":76.904296875}]}
2 | {"points":[{"lat":14.232437996569354,"lng":76.409912109375}, {"lat":13.336175186494927,"lng":77.1185302734375},{"lat":12.961735843534294,"lng":77.596435546875},{"lat":12.511665400971031,"lng":76.904296875}]}
I need to draw multiple polygon
but i am trying get this json into rails controller using
controller code
query="select id,description from clusters;
#result=ActiveRecord::Base.connection.execute(query);
The problem i am facing here how to pass this #result to javascript
to draw multiple polygon in google map.
if copy this json into one varible in js i able to draw cluster but problem i am facing how pass this json data from database reading in controller to javascript in rails
my google map code in javascript if hard code json into one varible it is working but i need take this json from database how to pass json with id from controller to javascript
var obj=i need json to store here //this how to fetch json from controller to js
polygons = [];
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
var arr = new google.maps.MVCArray();
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals].lat );
arr.push( new google.maps.LatLng( obj[i][ind][vals].lat, obj[i][ind][vals].lng ) );
}
}
polygons.push(arr);
}
polygons.forEach( function(polyPath) {
var polygon = new google.maps.Polygon({
paths: polyPath,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);

I would suggest an ajax-load for points. Then you can use the JSON-Output for rendering the action. It could be:
render json: #result
Other solution: When you have the googlemaps code in your view you could assign a json-string from the db to a javascript-variable:
var json_string = '<%= #results.raw %>';

Related

How to modify content of an array in Javascript

I'm using the Google Maps API to create some zones on a map. I stored the geodata in a database and I get it through Ajax.
Problem is that API wants the data as an object like :
var myHome = { "lat" : "44.767778" , "long" : "-93.2775" };
So I need to put in the array the {"lat" : and "long : ... };
How could I do that ?
Here is what I did with your help. I've got no error but nothing appears on the map. I used the example with BermudaTriangle from the API like a model : https://developers.google.com/maps/documentation/javascript/examples/polygon-autoclose
$.get(
"getZones.php", //Get geodata from database
function(data) {
locZone = data;
var reg=new RegExp("[/]+", "g"); //Separate points of the zone
var tableau=locZone.split(reg);
for (var i=0; i<tableau.length; i++) {
points = new google.maps.LatLng(tableau[i]);
coords.push(points);//Put the coordinates in a tab
}
var zone = new google.maps.Polygon({
paths: coords, //Use the tab like in the example from API
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
zone.setMap(map);
}
);
That's okay I just rewrote the loop :
for (var i=0; i<tableau.length; i++) {
var b=tableau[i].split(","); //Separate lat & lng
points=new google.maps.LatLng(parseFloat(b[0]), parseFloat(b[1])); //Convert data into float type
coords.push(points);
}
Probably the easiest way (without seeing any example code of you) is by putting the values you get via ajax in a new variable. Let's say the object you get is called geoData. geoData should have the 2 values lat and long or however you called them.
Simpliest way would be:
var myHome = {
"lat": geoData.lat,
"long": geoData.long
}
That's it, hope this helps.
You can also create a LatLng object directly through google maps api:
var latlng = new google.maps.LatLng(44.767778, -93.2775);
That returns the object what you need to work with the maps.

Google Maps API Polyline creation failing with "Uncaught TypeError: number is not a function"

I'm working a django project using the google maps JS api.
Basically what's going on here is that I'm creating a map centered at a point (works perfectly), drawing a bunch of points specified by the journey variable (value is substituted in by django template),
and then trying to draw a polyine between these points. (Fails to produce a polyline with a "Uncaught TypeError: number is not a function" at the JS console.)
The traceback at the JS console is pretty indecipherable to me, particularly due to all the .js files being minned.
When I log the path attribute of the polyline, and the coordinate I'm adding (as seen below), everything seems to work. I know the coord is formatted correctly, because I think Marker and Polyline should take the same datatype (LatLng) for their locations, and the Markers work fine. Anyone have any idea what's happening?
var mapOptions = {
center: { lat: 37.23112,
lng: -122.29398
},
zoom: 15
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Make the line that will trace the guys route:
var polyOptions = {
strokeColor: '#000000',
srokeOpacity: 1.0,
strokeWeight: 3
};
var poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Make an array of everywhere the lilguys has been. Passed into this django template as {"lat": 12, "lng": 8} objects.
var journey = [{"lat": 33.2389, "lng":-123.9349}, {"lat":32.928392, "lng":-122.29289}, {"lat":33.928982, "lng":-120.298392}];
var journey_markers = [];
// Draw all the placemarks
for (var i = 0; i < journey.length; i++) {
var coord = journey[i];
journey_markers.push(new google.maps.Marker({position: coord, map:map}));
var path = poly.getPath();
console.log(coord);
console.log(path);
path.push(coord);
}
Thank you!
EDIT:
I substituted the template variables in for what they evaluate to. This was checked by looking at the HTML source code in the browser, and confirmed to not be the source of the bug.
Figured out the answer. It seems to be that unlike Markers, the Polyine path requires google.maps.LatLng() objects rather than latlng literals.
The following fixes the issue:
...
// Draw all the placemarks
for (var i = 0; i < journey.length; i++) {
var coord = new google.maps.LatLng(journey[i].lat, journey[i].lng);
...

Unable to reuse polyOptions for new polygon

I'm working with the Google Maps v3 API, placing some polygons on the map. I create a 'polyOptions' object which is used when creating the polygon.
This only works once. For all other polygons, I have to create another identical 'polyOptions' object. Which is fine, but a bit repetitive, and this webpage is big enough already without repeating myself.
Have I misunderstood the nature of this JS object?
//Create array for polygons
var polygons = [];
//first polygon
var myCoordinates = [new google.maps.LatLng(55.81362907119961, -2.054443359375) //long list of coordinates
var polyOptions = {
path: myCoordinates,
strokeWeight: 1,
fillColor: "white",
fillOpacity: 0.6
}
var poly1= new google.maps.Polygon(polyOptions);
poly1.setMap(map);
polygons.push(poly1);
//second polygon
var myCoordinates = [new google.maps.LatLng(54.94607621987403, -3.16131591796875) // long list of coordinates
var poly2 = new google.maps.Polygon(polyOptions); // doesn't work
poly2.setMap(map);
polygons.push(poly2);
You must update the path property of your polyOptions at every step. At the moment your second polygon is drawn on the first with same coordinates.
// second polygon
// your var myCoordinates is already defined above, now use it by its name
myCoordinates = [new google.maps.LatLng(54.94607621987403, -3.16131591796875) // long list of coordinates
polyOptions.path = myCoordinates; // here you set path to the new value
var poly2 = new google.maps.Polygon(polyOptions); // should work
poly2.setMap(map);
polygons.push(poly2);

JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

i want to implement a google map based on its api. i want to add a path based on coordinates to it. therefore i get my coordinates from my model and want to iterate over the object to fille the map with this points. in my jade template i include the api js code like this:
script(type='text/javascript')
function initialize() {
var myLatLng = new google.maps.LatLng(0, -180);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var flightPlanCoordinates = [
- if (typeof(pins) != null)
- var.pins.forEach(function(pin) {
new google.maps.LatLng(pin.latitude, pin.longitude),
- })
new google.maps.LatLng(0,0)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
div#map_canvas(style='height: 500px; background-color: #990000;')
the problem is: jade renders this snippet
var flightPlanCoordinates = [
- if (typeof(pins) != null)
- var.pins.forEach(function(pin) {
new google.maps.LatLng(pin.latitude, pin.longitude),
- })
new google.maps.LatLng(0,0)
];
as it is in the jade template source... the - if etc. doesn't get parsed! any ideas?
thanks!
The entire script tag (everything indented under it) is going to be passed through raw without further parsing. Jade does HTML templating not HTML templating plus nested javascript templating. To pass your pins variable from jade local template variable data to script source code, you'll have to do some other approach like using raw jade to render a tiny script tag that just calls your initialize function with the pins data as a literal, or stick your pins data into the dom somewhere and then read it from there. Something along these lines below your script tag (pseudocode, haven't tested)
- if (typeof(pins) != null)
!= "<script type='text/javascript'>"
!= "var pins = [];"
- forEach pin in pins
!= "pins.push(new Pin(" + pin.latitude + ", " + pin.longitude + "));"
!= "initialize(pins);"
!= "</script>"
I passed the value as a hidden input element, e.g.:
input(type='hidden', id='variableName', value='#{variableName}')
Accessed via jQuery:
$("#variableName").val()
Joe
You can use this:
script
console.log(#{var_name});
the script tags are purely text, you can't easily mix the Jade to generate this javascript, it's usually a reflection of poor design. You can just serialize things as JSON that you need on the client or use express-expose to do this
server side
JSON.stringify(users)
client side
var users=JSON.parse(("#{users}").replace(/"/g,'"'));
I had a similar issue and this line of code solved it:
var myvar = !{JSON.stringify(mydata)};
The answer came originally from this post

How can I display this polygon on a Google Map?

I have some MultiPolygon data (the USA state of California) which I'm trying to display on a Google Map (v3 JavaScript API).
So I've tried to make it into some JSON data, and then display that MultiPolygon on a Google Map. It hangs and doesn't work.
Here's the jQuery I've used:
function getTestData() {
// Grab the California state data.
var request = $.getJSON("/Foo/Bar?format=json", function (results) {
// map it.
var polygon = createGeoJsonPolygon(results, "#FF7800", "#46461F");
polygon.setMap(map);
});
}
function createGeoJsonPolygon(geojson, strokeColour, fillColour) {
var coords = geojson.coordinates; // Array of polygons.
var paths = [];
$.each(coords, function (i, n) {
$.each(n, function (j, o) {
var path = [];
$.each(o, function (k, p) {
var ll = new google.maps.LatLng(p[1], p[0]);
path.push(ll);
});
paths.push(path);
});
});
return new google.maps.Polygon({
paths: paths,
strokeColor: strokeColour,
strokeOpacity: 1,
strokeWeight: 2,
fillColor: fillColour,
fillOpacity: 0.25
});
}
How can I draw my sample data on a Google Map? I'm not sure if my code is wrong or the data has been extracted incorrectly.
My post on Google Groups came to help save the day.
This is what was suggested :
function createGeoJsonPolygon(geojson, strokeColour, fillColour) {
var coords = geojson.coordinates; // Array of polygons.
var paths = [];
$.each(coords, function (i, n) {
var path = [];
$.each(n, function (j, p) {
var ll = new google.maps.LatLng(p[1], p[0]);
path.push(ll);
});
paths.push(path);
});
return new google.maps.Polygon({
paths: paths,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
}
You made the polygon; you didn't add it to any map.
Assuming map is a variable of type google.maps.Map, do this:
var poly = createGeoJsonPolygon( arg1, arg2, arg3 );
poly.setMap( map );
Also, note that your data (which you link to) is not (as you state) an array of points; it's an array of arrays of arrays of points.
Without encoding polygon contours, you can use only one contour per polygon, see docs: http://code.google.com/intl/ru/apis/maps/documentation/javascript/v2/reference.html#GPolygon.
It accepts only an array of points, not contours.
Read about polygon encoding for google maps, there is a readymade js for that.
edit:
docs for v3:
http://code.google.com/intl/ru/apis/maps/documentation/javascript/reference.html#PolygonOptions

Categories

Resources