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'}}]
Related
The Server side uses python with flask, and the html template is jinja2. I'm trying to make a marker with google api. The latitude and longitude information are stored in stores[][] which is passed from python. This code is between <script> tag in my html file and it works fine.
var marker = new google.maps.Marker({position: {lat: {{stores[0][5]}}, lng: {{stores[0][6]}}}, map: map});
var marker = new google.maps.Marker({position: {lat: {{stores[4][5]}}, lng: {{stores[4][6]}}}, map: map});
I have multiple lat,lng from which I want to make markers, so I put it inside a for loop.
var i;
for (i = 0; i < 5; i++) {
var marker = new google.maps.Marker({position: {lat: {{stores[i][5]}}, lng: {{stores[i][6]}}}, map: map});
}
Exactly same code, but the index is i was put instead of a number for indexing. It suddenly gives errors saying
jinja2.exceptions.UndefinedError: list object has no element Undefined
I double checked that stores[][] have more than 5 elements. This is very very confusing.
You can't do this. Jinja is evaluated entirely on the server, well before the JS can run on the client. There is no way for Jinja to have access to variables from the JS code.
You should move the loop to Jinja itself.
{% for store in stores %}
var marker = new google.maps.Marker({position: {lat: {{ store[5] }}, lng: {{ store[6] }}}, map: map});
{% endfor %}
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.
I've got a project with a django backend that I'm using for logins, and using the mysql DB through my local host. I currently have my gettweets.py script returning an array of coordinates and have a JS script that is supposed to get these results and plot it to google maps api. My JS script fails at $.get. However, if i go to 127.0.0.1/gettweets?tag=%23Pizza, I get something like this:
["-87.634643, 24.396308", "-80.321683, 25.70904", "-79.639319, 43.403221", "-95.774704, 35.995476", "-84.820309, 38.403186", "-120.482386, 34.875868", "-121.385009, 38.716061", "-111.530974, 40.619883"]
I've been trying to get JS to make the call on the button click because I don't think I can get the results to it through Django. Why is it getting stuck?
Here is the JS inside of index.html
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(49.13,-100.32),
mapTypeId: 'roadmap'
});
}
// Loop through the results array and place a marker for each
// set of coordinates.
$('#searchButton').click(function(){
$.get('../../gettweets?tag=%23Trump', function(data, status) {
alert(status);
var data = JSON.parse(this.response);
alert('data');
data.forEach(function(point) {
var coordString = point['coord'];
var x = coordString.substring(0,coordString.indexOf(','));
var y = coordString.substring(coordString.indexOf(',')+1,coordString.length);
console.log(x);
console.log(y);
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(x,y);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
});
window.myLine.update();
});
//xmlhttp = new XMLHttpRequest();
//var tag = document.getElementById('tagSearch').value;
//if (this.readyState === 4 && this.status === 200) {
//}
//xmlhttp.open("GET","./getTweets.php?tag='" + tag + "'");
//xmlhttp.send();
});
</script>
Button/form:
<form>
<input id="tagSearch" type="text" name="tag" maxlength="100" required placeholder="{{ tag }}" />
<button class="btn waves-effect red" type="submit" id="searchButton" name="search">Submit
<i class="material-icons right">send</i>
</button>
</form>
gettweets.py - NOTE I've got this in my views, as well as a separate file. I'm not sure which one I need with the JS
def tweets(request):
tag = request.GET['tag']
print(tag)
x = models.Tweet.objects.filter(tag=tag)
print(x)
coords = []
for i in x:
coords.append(i.coord)
print(coords)
return JsonResponse(coords, safe=False)
Finally, urls
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^gettweets$', views.tweets, name='gettweets'),
]
You're calling $.get() incorrectly. Its signature is $.get(url[, data][, success][, dataType]), from the docs.
I would prefer using a settings object like so:
$.get({
url: '../../gettweets?tag=%23Hillary',
success: function (data, status) {
...
}
});
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>
I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.
For example:
City can be 'miami, US' or city can be 'miami, united states'
How do I print its latitude?
You can find the code jsfiddled here : http://jsfiddle.net/YphZw/
or below :
$("#btn").click(function(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>
If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/
The code I wrote is inspired from the geocoding-simple sample.
Regards.
EDIT 1:
You can achieve it using an non-official PHP library. Check this example :
http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php
(The code is at the bottom=
You can use Google's geocoding service, e.g.,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.
The API docs are at:
https://developers.google.com/maps/documentation/geocoding/
Update per comment below: Doesn't work after July 2018.
This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLng coords, and put markers on a map:
// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
const centerOfUS = {
lat: 37.09024,
lng: -95.712891
}
// Create a map object and specify the DOM element for display.
const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
center: centerOfUS,
scrollwheel: false,
zoom: 4
})
// Create a marker and set its position.
const geocoder = new google.maps.Geocoder()
// Filter out duplicate cityStates
let cityStates = {}
document.querySelectorAll('.nearby_event_city_state').forEach(event => {
cityStates[event] = event.innerText
})
// `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
for (const cityState in cityStates) {
const location = cityStates[cityState]
geocoder.geocode({
address: location
}, function (results, status) {
if (status === 'OK') {
const result = results[0].geometry.location
const lat = result.lat()
const lng = result.lng()
const latLng = {
lat,
lng
}
return new google.maps.Marker({
map: map,
position: latLng
})
}
})
}
}
// /Nearby Events with Google Maps
Make sure to include your <script> tags.
<script src="/dist/js/main.js"></script>
<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>
StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...