polygon color changes automatically when zooming map - javascript

I have implemented a google map using V3 js API. I am drawing about 500 zip code polygons inside the map. The colouring of the zip code polygons depends upon certain conditions which is working fine. Like I am assigning distinct colours to a set of zipcodes. But the problem is when I am zooming in the map some of the zipcode polygon colours getc changed. How can we fix it.
Here is the code
{% ifequal zip.rank 1 %}
var fillColor = '#FF0000';
{% endifequal %}
{% ifequal zip.rank 2 %}
var fillColor = '#FF00D3';
{% endifequal %}
{% ifequal zip.rank 3 %}
var fillColor = '#BE4BAA';
{% endifequal %}
{% ifequal zip.rank 4 %}
var fillColor = '#BE88B5';
{% endifequal %}
{% ifequal zip.rank 5 %}
var fillColor = '#857081';
{% endifequal %}
var path = [
{% for polycoord in zip.zip_info.zip_polygon %}
new google.maps.LatLng({{polycoord.1}}, {{polycoord.0}}),
{% endfor %}
];
var polygon = new google.maps.Polygon(
{
path:path,
clickable:true,
strokeColor: '#000000',
strokeOpacity: 0.75,
strokeWeight: 1,
fillColor: fillColor,
fillOpacity: 1,
}
);
polygon.setMap(map);

Related

how to get content in same div without getting in many boxes?

I have following code
<div class="col-md-9">
<div id="statbox">
{% for obj in product_type %}
{% for obj1 in vastu %}
<script type="text/javascript">
var product = "{{ obj.type_product }}";
var product1 = "{{ name }}";
var vastu = "{{ obj1.vastu_key.id }}";
var type_id = "{{ obj.id }}";
if (vastu == type_id)
{
var title = "{{ obj1.title }}";
var brand = "{{ obj1.brand }}";
var img = "{{ obj1.image }}";
var price = "{{ obj1.price }}";
$("#statbox").prepend("<div id='box2'>"
+ title
+ brand
+ price
+"</div>");
}
</script>
{% endfor %}
{% endfor %}
</div>
I am using two for loops here and the box2 which is styled in css, by running this code i got box2 multiple times as content contains in child for loop and that title,brand,img,price is displyed in each new box2.
But i want new box2 should be generate only according to content contains in parent for loop not according to content contains in child for loop
and the all contents i.e. title,brand,img,price which are associated with each content of parent for loop should disply in same box2.
Multiple box2 only create according to parent for loop and contents of child for loop in the same box2 created by parent for loop.
Thank you....
Create a JS object and loop that . Also change the ID to class
Something like this:
var boxes = [
{% for obj in product_type %}
{
{% for obj1 in vastu %}
"product":"{{ obj.type_product }}",
"product1":"{{ name }}",
"vastu": "{{ obj1.vastu_key.id }}",
"type_id":"{{ obj.id }}"
{% if obj1.vastu_key.id == obj.id %}
,
"title":"{{ obj1.title }}",
"brand":"{{ obj1.brand }}",
"img":"{{ obj1.image }}",
"price":"{{ obj1.price }}"
{% endif %}
{% endfor %}
}
{% endfor %}
];
$.each(boxes,function(obj) {
$("#statbox").prepend("<div class='box2'>"
+ obj.title || ""
+ obj.brand || ""
+ obj.price || """
+"</div>");
});

How to set jQuery variable as a django template variable

I'm using a jQuery script inside of a Django template in order to render a Google Map. The goal is to plot multiple markers on the map. I've tried two things:
Set the jQuery var to a Django template variable, which I defined as a list in views.py. Was not able to produce any markers in this case. Just a blank map.
var markers = {{ marker_list }};
I printed marker_list on the page to confirm, which was this in my last test: marker_list = [['Chiang Mai Park', 21.0333, 21.0333], ['Ho Chi Minh Mausoleum', 21.036666667, 21.036666667]]
Make a for loop with template tags inside the jQuery script, and build the list with template variables. With this, only one marker will plot, even if there are multiple locations in the list (see marker_list above).
{% for instance in queryset %}
var markers = [
[{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]
];
{% endfor %}
Full code is below showing attempt #2. Note that "var markers" in the javascript requires a list of a lists. i.e. var markers = [[name1, latitude1, longitude1], [name2, latitude2, longitude2]].
Any help would be much appreciated. I'm both a Django and Javascript n00b.
views.py
def places_map(request):
if request.user.is_authenticated():
queryset = AddLink.objects.filter(user=request.user)
marker_list = []
for instance in queryset:
name = str(instance.location)
latitude = float(instance.place_lat)
longitude = float(instance.place_lat)
marker_list += [[name, latitude, longitude]]
context = {
"queryset": queryset,
"marker_list": marker_list
}
return render(request, "places_map.html", context)
else:
raise Http404("You must be logged in to view places.")
places_map.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load staticfiles %}
<style>
{% block style %}
#map_wrapper {
height: 400px;
}
#map_canvas {
width: 100%;
height: 100%;
}
{% endblock style %}
</style>
{% block content %}
<div class='row' align='center'>
<h1 id="places-title">Map</h1>
{% if queryset %}
<!-- removed -->
{% endif %}
</div>
<div id="map_wrapper">
<div id="map_canvas" class="mapping"></div>
</div>
<!-- For testing -->
{{ marker_list }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// Script from http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
{% for instance in queryset %}
var markers = [
// ['London Eye, London', 51.503454,-0.119562],
// ['Palace of Westminster, London', 51.499633,-0.124755],
// ['Ministry of Sound', 51.498231,-0.118468],
[{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]
];
{% endfor %}
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<h3>London Eye</h3>' +
'<p>The London Eye is a giant...</p>' + '</div>'],
['<div class="info_content">' +
'<h3>Palace of Westminster</h3>' +
'<p>The Palace of Westminster is the...</p>' +
'</div>'],
['<div class="info_content">' +
'<h3>Ministry of Sound</h3>' +
'<p>Nice place.</p>' +
'</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2], markers[i][3]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
</script>
{% endblock content %}
You should use JSON for this.
context = {
"queryset": queryset,
"marker_list": json.dumps(marker_list)
}
and in your template, use the safe filter so Django doesn't escape the symbols:
var markers = {{ marker_list|safe }}
By doing {{ marker_list }} you just end up with a string which is obviously no good, the solution I normally go with is to define a blank array and then append to it
var markers = [];
{% for instance in queryset %}
markers.append([{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]);
{% endfor %}
Of course you could just close the array after the for loop, this can produce a jslint error although it should work just as well.
var markers = [
{% for instance in queryset %}
[{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}],
{% endfor %}
];

how to get values from views.py and use it in Javascript tag

This is my views.py
def list_note(request):
note_info = Note.objects.filter(id_teacher__exact=request.user.id).select_related()
actual_date = date.today()
for notes in note_info:
note_date = notes.remind.date()
tmp = actual_date + timedelta(days=3)
note_expired_list = []
if tmp == note_date:
print()
else:
note_expired_list.append(notes)
print(note_expired_list)
note_data = {
"note_details": note_info,
"note_expired_list_details": note_expired_list,
}
return render_to_response('list_note.html', note_data, context_instance=RequestContext(request))
I want use value note_expired_list_details in <scrpit> tag to display this in alert. How do this?
I try use {{ note_expired_list_details}} but in <script> tag not work.
This is a part of my templates (I try finding HTML element by Id in JS)
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div >
{% for details in note_expired_list_details %}
<p>{{ details }}</p>
{% endfor %}
<script>
var x = document.getElementsByTagName("p");
alert("Test\n" + x[1].childNodes.nodeValue + "\n");
</script>
</div>
{% endblock %}
Why not store value of {{ note_expired_list_details }} in a JS variable and then use it however you want?
<script>
var expiredList = '{{ note_expired_list_details }}';
alert(expiredList);
</script>

Allow to only purchase only one product # Shopify

We're looking for a solution to hide the add to cart button if a product is already in cart. So that the user can not order more than 1 of each product.
A Mentor from Codementor wrote a function which hides the Add to Cart button if a selected variant is in the cart:
var updateCartButtons = function () {
if (typeof (window.cartItems) === "undefined") {
window.cartItems = [];
}
var cartItemVariantID, selectedVariantID, selectedVariantName;
selectedVariantName = $('.swatch :radio:checked').val();
selectedVariantID = $('#product-select option').filter(function () {
return $(this).text() === selectedVariantName;
}).val();
$('.buymarginsecond').removeClass('addedToCart');
for (var i = 0, l = cartItems.length; i < l; i++) {
cartItemVariantID = cartItems[i].variant_id;
if (cartItemVariantID == selectedVariantID) {
$('.buymarginsecond').addClass('addedToCart');
break;
}
}
};
We'd like to change this function to the effect that the
button disappears as soon as the main product is in the cart.
So you can only order one of each product and not different variants of the product.
You can use this code in your product.liquid file where add to cart is button is show. It will loop through the titles in the cart and if found set the variable to yes. Then check if variable is no, not in cart and show add to cart.
{% assign in_cart = 'no' %}
{% for item in cart.items %}
{% if item.product.title == product.title %}
{% assign in_cart = 'yes' %}
{% endif %}
{% endfor %}
{% if in_cart == 'no' %}
// SHow Add to Cart
{% endif %}

Javascript not reading the keys and values of a dictionary in django template

I have a dictionary like:
dest = {2: [u'canada', u'A', 'Ottawa'], 5: [u'Malaysia', u'A', 'KualaLumpur'],...}
Then I tried to retrieve the keys and values from dest in django template using javascript:
function categorizeReports()
{
var a = [];
var b = [];
{% for i,v in dest %}
id = '{{i}}';
console.log('id', id)
values = '{{v}}';
console.log('values',values)
{% for name, type, cat in values %}
if(type=='A' && cat=='Ottawa')
{
a.push(id,name,type,cat)
}
if(type=='A' && cat=='KualaLumpur')
{
b.push(id,name,type,cat)
}
{% endfor %}
{% endfor %}
console.log(a)
console.log(b)
}
But both the Arrays are shown as 'an empty string' as well as id and values are too shown as 'an empty string', Please help!
Missing .items
Change
{% for i,v in dest %}
to
{% for i,v in dest.items %}

Categories