Add markers from rails database - javascript

I'm creating a map with Google Maps API to reference restaurants based on their location. Each restaurant in my database (sqlite3) has a title, a description and two coordinates (latitude, longitude). I can successfully create entries in my database but struggle to find a solution to call in JS each restaurant's coordinates from the database.
Different solutions have been proposed on Stackoverflow of which this one, another and a last one, but none of the answers my question as I'm working exclusively with JS and Ruby (on rails).
Would you have suggestions ?

First, you need to read this example from Goolge Maps Javascript API and play with this code:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&callback=initMap">
</script>
</body>
</html>
As you can see here, you need to
create your own GOOGLE_MAPS_API_KEY here
create div with id;
connect Google's javascript, which when will load, will load also js-function initMap()
define initMap-function with map and marker settings.
Next step: getting data from database and passing to JavaScript.
I used gon gem for transferring data from backend to frontend:
in controller:
# app/controllers/application_controller.rb
def root
gon.locations = Location.all
end
in layout:
<!-- app/views/layouts/application.html.erb -->
<head>
<%= include_gon %>
<!-- ... -->
</head>
in view:
<!-- app/views/application/root.html.erb -->
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: { lat: gon.locations[0].lat, lng: gon.locations[0].lng }
});
for(var i = 0; i < gon.locations.length; i++){
new google.maps.Marker({
position: { lat: gon.locations[i].lat, lng: gon.locations[i].lng },
title: gon.locations[i].name,
map: map
});
}
}
<script>
But, if you don't want use gon gem for passing data from backend to frontend, you can do this by plain rails:
# app/controllers/application_controller.rb
def root
#json_data = {
locations: {
# ...
},
# ...
}.to_json
end
<!-- views/posts/edit.html.erb -->
<script>
var json_data = JSON.parse('<%= raw(escape_javascript(#json_data)) %>');
</script>
Also, I created rails demo application, you can play with it.
This commit doing all job, to write 'ICE' word by markers on Antarctica.
See these files for more details:
app/controllers/application_controller.rb
app/views/application/root.html.erb
app/views/layouts/application.html.erb
I used this online service to create coordinates for 'ICE' word

One way you could try is by using json. For example in the controller.
class RestaurantsController < ApplicationController
def show
#restaurant = Restaurant.find(params[:id])
respond_to do |format|
format.html
format.json {render json: #restaurant}
end
end
end
Then the restaurant can be accessed in javascript (I'll use JQuery)
$.getJSON("show_page_url.json", function(data){
//data will contain the #restaurant object
//so data.latitute should return the value
}
Maybe this helps. I used it for a simple project I did recently, but maybe there are better methods.

To make variables in your rails app accessible for js code, you need to save these values in rendered html and later your js code can take values from html. You can use gon so you don't have to write the solution yourself. Here are the steps to get it working:
install the gem 'gon'.
add <%= Gon::Base.render_data %> to your layout.
set variable: gon.push(restaurants: restaurants).
in your js code, read data and pass it to your map.

Related

how to send longitude and latitude to javascript script from def django

I can't figure out how to replace digital longitude and latitude values with dynamic fields from postgres in javascript
how to get the longitude and latitude of a particular place in this script?
<div id='map' style='width: 100%; height: 400px;'></div>
<script>
mapboxgl.accessToken = '{{ mapbox_access_token }}';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [20.890438, 52.256002],
// {{venue.lat}}, {{venue.long}} How to pass fields in a similar way as all other django fields
zoom: 9
});
var marker= new mapboxgl.Marker()
.setLngLat([20.890438, 52.256002])
// {{venue.lat}}, {{venue.long}}
.addTo(map)
</script>
All rendering functions in django. Here's how to send a specific longitude and latitude for a specific event.
def show_venue(request, venue_id):
venue = Venue.objects.get(pk=venue_id)
venue_owner = User.objects.get(pk=venue.owner)
long = Venue.objects.get(pk=venue.long)
lat = Venue.objects.get(pk=venue.lat)
#addresses = Venue.objects.all()
mapbox_access_token = 'pk.eyJ1IjoicGF2ZWxzdHJ5a2hhciIsImEiOiJjbDI2ZmJmcTkyajBwM2lscDd6aDVwOG4xIn0.15o8i7eD1qwyQcnsx2iBmg'
return render(request,
'events/show_venue.html', {
'venue': venue,
'venue_owner':venue_owner,
#'addresses': addresses,
'mapbox_access_token': mapbox_access_token,
'lat':lat,
'long':long,
})
I will be very grateful for your help
In Django i would write like this
{{venue.long}} {{venue.lat}}
and in JavaScript it should be like this
['{{venue.long}}','{{venue.lat}}']
If the problem is the format, you can try this:
center: [{{venue.lat|floatformat:'5'}}, {{venue.long|floatformat:'5'}}]

how can to convert array from jsp to javascript

please i work in project and i want to display many markers on map , i want to display arr[][] from jsp to javascrpit like this code,
please i work in project and i want to display many markers on map , i want to display arr[][] from jsp to javascrpit like this code
for ex:
i want to replace this code :
for (var i = 0; i < 3; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( 17.088291,78.442383 ),
map: map,
});
to :
for (var i = 0; i < 3; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( arr[i][0],arr[i][1] ),
map: map,
});
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD4DvaNOnpTRUFASvy6lyY0DDVcfXytvnY&libraries=places&&callback=initMap">
</script>
<script>
<%!
double arr[][]= new double[3][2];
%>
<%
arr[0][0]=19.088291;
arr[0][1]= 78.442383;
arr[1][0]=18.088291;
arr[1][1]=78.442383;
arr[2][0]=17.088291;
arr[2][1]=78.442383;
%>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(19.373341, 78.662109),
zoom:7
}
var map=new google.maps.Map(document.getElementById("sample"),mapOptions);
//animation:google.maps.Animation.BOUNCE
for (var i = 0; i < 3; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( 17.088291,78.442383 ),
map: map,
});
}
}
</script>
</head>
<body onload="loadMap()">
<div id="sample" style="width:580px;height:400px;"></div>
</body>
</html>
the simple answer
add this line in jsp code
String json = new Gson().toJson(array);
and in javascript add this line
var arr=<%=json%>;
code will work
I think you have got two options here:
A. Use out.print in the loop, it I think you already tried that but forgot something very important - <% and %>
So the final line of code should look like:
new google.maps.LatLng(<% out.print(arr[i][0]); %>, <% out.print(arr[i][1]); %>
B. Convert the whole JSP array to JSON and decode back. Although not the simplest solution but can be useful in many places like external services etc. You can use a library like Gson.

Django google-maps API v3 doesn't work with Chrome when using template variables

I want to pass latitude,longitude variables to my template to show location on Google Maps. For that i use template variables in javascript:
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {lat: {{ m_city.location.y }}, lng: {{ m_city.location.x }}},
zoom: 10
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>
It works fine in Firefox, but Chrome(v.42) doesn't show map at all. Although in source code of generated page latitude and longitude are correctly substituted.
If i copy generated latitude and longitude and hard code it in template then code works and Chrome displays map.
Can anyone point me to why this is happening?
UPDATE
As Selcuk pointed in comments, problem was in decimal separator(comma instead of point). Different separators were generated because of different language settings of browsers. Setting USE_L10N to False helped.
I suggest to use localize templatetag, so you can use format localisation without breaking your javascript code.
{% localize off %}
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {lat: {{ m_city.location.y }}, lng: {{ m_city.location.x }}},
zoom: 10
});
}
</script>
{% endlocalize %}
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>

Rewrite part of javascript with C#

I'm writing this program in C# which should display Google Maps. I'm using the Google Maps JavaScript API which is the best one I could find. With the program you should be able to search for places.
The code:
window.onload = function() {
var latlng = new google.maps.LatLng(52.785804, 6.897585);
var options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
}
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#map {
width: 80%;
height: 100%;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Google Maps</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="map">
</div>
</body>
</html>
Am I in some way able to edit the latlng using C#? Or does someone know an alternative way to use the Google Maps API with C#?
If you are not using MVC or other server side technologies on this specific page your only option would be to load the lat/long from an AJAX call.
$.ajax({
url: "url/to/your/api/that/returns/lat/long",
success: function(result) {
// process your JSON result and set the lat/long
}
});
the API can be written on the server side using any language (including c#)
To display Google map in a Desktop application, e.g. Winforms, you may use a WebBrowser control and an HTML page (local file or embedded as resource).
It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.
Javascript to C#
-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }
-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />
C# to Javascript
-------C# code--------------------
object [] MyArgs = { "Hello" } ; WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;
-------Javascript----------------
function MyJsFunction(s) { alert(s) ; }

Google maps v3 api, center map based on location

I'm trying to center my map based on the location of the visitor, but somehow it doesn't work.
I have a PHP variable containing the country code of my visitor, which works fine when i check the source code in my browser. It looks like this;
<head>
...
<script type="text/javascript">
var lang = <?php echo $lang; ?>;
</script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="initialize()">
...
My script.js contains these lines;
function initialize() {
if (lang == NL) {
var centerlat = 52.150892;
var centerlng = 5.534668;
var zoomlvl = 7;
}
else {
var centerlat = 52.367896;
var centerlng = 5.219407;
var zoomlvl = 13;
}
var myLatlng = new google.maps.LatLng(centerlat,centerlng);
var myOptions = {
zoom: zoomlvl,
center: myLatlng,
...
}
map = new google.maps.Map(document.getElementById("kaart"), myOptions);
When i load the page containing the map it just doesnt appear. In the source code i can see the PHP variable displaying correctly.
Firebug says lang is undefined. Any idea whats going on here?
//edit: I have another variable done in the same way which works fine. But its outside the initialize function.
Solved: Forgot quotes ^^
Try surround NL with "".
As an aside have you looked into HTML 5 geolocation? Its relatively simple to implement and will give you a much more accurate location.
Take a look here: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation and here:http://www.w3schools.com/html/html5_geolocation.asp
Any idea whats going on here?
sorry, I don't have the rep to 'comment'
Is NL a string variable or a value (should it be "NL" ?)

Categories

Resources