Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

05 assignment #50

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 36 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,53 @@
from flask import Flask
from flask import render_template
from flask import request
from flask import Response

import json
import time
import sys
import random

import pyorient

from Queue import Queue

app = Flask(__name__)

q = Queue()

def event_stream():
while True:
result = q.get()
yield 'data: %s\n\n' % str(result)

@app.route('/eventSource/')
def sse_source():
return Response(
event_stream(),
mimetype='text/event-stream')

@app.route("/")
def index():
return render_template("index.html")

@app.route("/getData/")
def getData():

# TRY TO SEND BACK OTHER MESSAGES FROM THE SERVER.
# MAKE SURE THE MESSAGES ARE BEING DISPLAYED ON THE FRONT END.
q.put("starting data query...")

lat1 = str(request.args.get('lat1'))
lng1 = str(request.args.get('lng1'))
lat2 = str(request.args.get('lat2'))
lng2 = str(request.args.get('lng2'))

print "received coordinates: [" + lat1 + ", " + lat2 + "], [" + lng1 + ", " + lng2 + "]"

client = pyorient.OrientDB("localhost", 2424)
session_id = client.connect("root", "password")
db_name = "property_test"
session_id = client.connect("root", "admin")
db_name = "soufun"
db_username = "admin"
db_password = "admin"

Expand All @@ -28,17 +57,14 @@ def getData():
else:
print "database [" + db_name + "] does not exist! session ending..."
sys.exit()

lat1 = 22.532498
lat2 = 22.552317

lng1 = 114.044329
lng2 = 114.076644

query = 'SELECT FROM Listing WHERE latitude BETWEEN {} AND {} AND longitude BETWEEN {} AND {}'

records = client.command(query.format(lat1, lat2, lng1, lng2))

random.shuffle(records)
records = records[:100]

numListings = len(records)
print 'received ' + str(numListings) + ' records'

Expand All @@ -55,6 +81,8 @@ def getData():

output["features"].append(feature)

q.put('idle')

return json.dumps(output)

if __name__ == "__main__":
Expand Down
193 changes: 154 additions & 39 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<html>
<head>
<title>Flask Demo</title>
<title>DMC Web Stack</title>
<script type="text/javascript" src="./static/lib/d3.js"></script>
<script type="text/javascript" src="./static/lib/leaflet.js"></script>
<link rel="stylesheet" href="./static/lib/leaflet.css" />
Expand All @@ -9,15 +9,65 @@
body {
padding: 0;
margin: 0;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
line-height: 18px;
}
html, body, #map {
height: 100%;
}

/*EXPERIMENT WITH DIFFERENT STYLING FOR THE CIRCLES AND WHAT HAPPENS WHEN THE MOUSE HOVERS OVER THEM*/
circle {
fill-opacity: 0;
stroke: red;
stroke-width: 5px;
fill-opacity: .2;
fill: black;
stroke-width: 0px;
}
circle:hover {
stroke: red;
stroke-width: 2px;
cursor: crosshair;
}
circle2 {
fill-opacity: .2;
fill: red;
stroke-width: 0px;
}
circle2:hover {
stroke: black;
stroke-width: 2px;
cursor: crosshair;
}


/*EXPERIMENT WITH YOUR OWN STYLING RULES TO CHANGE THE APPEARANCE OF THE TOOLTIP, THE MENU, AND THE MESSAGE TEXT*/
div.tooltip{
padding: 6px;
background: black;
visibility: hidden;
position: absolute;
z-index: 10;
}
p.tooltip-text{
margin: 0px;
padding: 0px;
color: red;
}

div.menu{
position: fixed;
margin: 0px;
padding: 10px;
top: 0px;
right: 0px;
width: 200px;
height: 500px;
background: rgba(255,255,255,.8);
}

em{
color: red;
font-weight: bold;
}
</style>

Expand All @@ -28,23 +78,60 @@

<div id="map"></div>

<!-- CHANGE THE STRUCTURE OF THE TOOLTIP TO DISPLAY THE LATITUDE AND LONGITUDE OF EACH POINT. ALSO, YOU COULD TRY TO DISPLAY ANOTHER PIECE OF DATA ABOUT THE POINT, BUT REMEMBER YOU FIRST NEED TO MAKE SURE TO SEND THIS DATA BACK FROM THE SERVER -->
<div class="tooltip">
<p class="tooltip-text" id="latitude">This is the latitude</p>
<p class="tooltip-text" id="longitude">This is the longitude</p>
</div>

<!-- EXPERIMENT WITH OTHER FORM ELEMENTS, AND ADD SOME TEXT TO THE MENU TO EXPLAIN WHAT IS HAPPENING ON THE SITE -->
<div class="menu">
<p><h4>DMC Web Stack</h4></p>
<form>
<p><input id="heatmap" type="checkbox">Heat Map</p>
<p><input type="button" value="Update Data" onclick="updateData()"></p>
<p>Status: <em id="message"></em></p>

<p><input id="colourChange" type="checkbox">Colour Change</p>
<p><input type="button" value="Update Data" onclick="updateData()"></p>
<p>Status: <em id="message"></em></p>
</form>
</div>


<script type="text/javascript">

var eventOutputContainer = document.getElementById("message");
var eventSrc = new EventSource("/eventSource");

eventSrc.onmessage = function(e) {
console.log(e);
eventOutputContainer.innerHTML = e.data;
};

// DON'T FORGET TO CHANGE THIS CODE DEPENDING ON THE DATA YOU'RE DISPLAYING IN YOUR TOOLTIP
var tooltip = d3.select("div.tooltip");
var tooltip_latitude = d3.select("#latitude");
var tooltip_longitude = d3.select("#longitude");


var map = L.map('map').setView([22.539029, 114.062076], 16);

//function cC() {

//if (document.getElementById('colourChange').checked) {



//} else {//


//this is the OpenStreetMap tile implementation

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

//uncomment for Mapbox implementation, and supply your own access token

// L.tileLayer('https://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={accessToken}', {
// attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
// mapid: 'mapbox.light',
// accessToken: [INSERT YOUR TOKEN HERE!]
// }).addTo(map);

//create variables to store a reference to svg and g elements

Expand All @@ -63,44 +150,72 @@
var transform = d3.geo.transform({point: projectStream});
var path = d3.geo.path().projection(transform);

d3.json("/getData/", function(data) {
function updateData(){

var mapBounds = map.getBounds();
var lat1 = mapBounds["_southWest"]["lat"];
var lat2 = mapBounds["_northEast"]["lat"];
var lng1 = mapBounds["_southWest"]["lng"];
var lng2 = mapBounds["_northEast"]["lng"];

request = "/getData?lat1=" + lat1 + "&lat2=" + lat2 + "&lng1=" + lng1 + "&lng2=" + lng2

console.log(request);

d3.json(request, function(data) {

//create placeholder circle geometry and bind it to data
var circles = g.selectAll("circle").data(data.features);

//create placeholder circle geometry and bind it to data
var circles = g.selectAll("circle").data(data.features);
circles.enter()
.append("circle")
.on("mouseover", function(d){
tooltip.style("visibility", "visible");
tooltip_latitude.text("latitude:" + d.geometry.coordinates[0]);
tooltip_longitude.text("longitude: " + d.geometry.coordinates[1]);
})
.on("mousemove", function(){
tooltip.style("top", (d3.event.pageY-10)+"px")
tooltip.style("left",(d3.event.pageX+10)+"px");
})
.on("mouseout", function(){
tooltip.style("visibility", "hidden");
})
;

circles.enter()
.append("circle")
.attr("r", 10);
// function to update the data
function update() {

// function to update the data
function update() {
// get bounding box of data
var bounds = path.bounds(data),
topLeft = bounds[0],
bottomRight = bounds[1];

// get bounding box of data
var bounds = path.bounds(data),
topLeft = bounds[0],
bottomRight = bounds[1];
var buffer = 50;

var buffer = 50;
// reposition the SVG to cover the features.
svg .attr("width", bottomRight[0] - topLeft[0] + (buffer * 2))
.attr("height", bottomRight[1] - topLeft[1] + (buffer * 2))
.style("left", (topLeft[0] - buffer) + "px")
.style("top", (topLeft[1] - buffer) + "px");

// reposition the SVG to cover the features.
svg .attr("width", bottomRight[0] - topLeft[0] + (buffer * 2))
.attr("height", bottomRight[1] - topLeft[1] + (buffer * 2))
.style("left", (topLeft[0] - buffer) + "px")
.style("top", (topLeft[1] - buffer) + "px");
g .attr("transform", "translate(" + (-topLeft[0] + buffer) + "," + (-topLeft[1] + buffer) + ")");

g .attr("transform", "translate(" + (-topLeft[0] + buffer) + "," + (-topLeft[1] + buffer) + ")");
// update circle position and size
circles
.attr("cx", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).x; })
.attr("cy", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).y; })
.attr("r", function(d) { return Math.pow(d.properties.price,.3); });
};

// update circle position and size
circles
.attr("cx", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).x; })
.attr("cy", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).y; });
};
// call function to
update();
map.on("viewreset", update);
});

// call function to
update();
map.on("viewreset", update);
};

});
updateData();

</script>

Expand Down