I've been able to import some shapefiles to Neo4j 2.3.1.
Now how do I view this data on a map?
I have tried the Wiki instructions on GeoServer and uDig, but both of them are outdated and I couldn't get it to work.
Is there any recent tutorial or other tool that can solve this problem?
I've used neo4j-spatial with Mapbox.js for visualizing geometries in a map.
For my use case I indexed US Congressional district geometries in neo4j-spatial then query the spatial index based on where a user clicks on the map, returning the closest district including the WKT string and the results of a Cypher query. To render the WKT polygon in the map I wrote a simple javascript function to parse that into an array of points to add a map annotation.
Here are some relevant code snippets:
Create the map and define a click handler for the map:
L.mapbox.accessToken = MB_API_TOKEN;
var map = L.mapbox.map('map', 'mapbox.streets')
.setView([39.8282, -98.5795], 5);
map.on('click', function(e) {
clearMap(map);
getClosestDistrict(e);
});
Handle mouse click
/**
* Find the District for a given latlng.
* Find the representative, commitees and subjects for that rep.
*/
function infoDistrictWithinDistance(latlng, distance) {
var districtParams = {
"layer": "geom",
"pointX": latlng.lng,
"pointY": latlng.lat,
"distanceInKm": distance
};
var districtURL = baseURI + findGeometriesPath;
makePOSTRequest(districtURL, districtParams, function (error, data) {
if (error) {
console.log("Error");
} else {
console.log(data);
var params = {
"state": data[0]["data"]["state"],
"district": data[0]["data"]["district"]
};
var points = parseWKTPolygon(data[0]["data"]["wkt"]);
makeCypherRequest([{"statement": subjectsQuery, "parameters": params}], function (error, data) {
if (error) {
console.log("Error");
} else {
console.log(data);
var districtInfo = data["results"][0]["data"][0]["row"][0];
districtInfo["points"] = points;
districtInfo["state"] = params["state"];
districtInfo["district"] = params["district"];
console.log(districtInfo);
addDistrictToMap(districtInfo, latlng);
}
});
}
});
Parse WKT into an array of points
/**
* Converts Polygon WKT string to an array of [x,y] points
*/
function parseWKTPolygon(wkt) {
var pointArr = [];
var points = wkt.slice(10, -3).split(",");
$.each(points, function(i,v) {
var point = $.trim(v).split(" ");
var xy = [Number(point[1]), Number(point[0])];
pointArr.push(xy)
});
return pointArr;
}
The code is in this repo. You can see the simple map demo here (just click anywhere in the US to get started). There is also a recent blog post about this example here.
Related
I have been struggling with this piece of javascript for some time now. I have read different, and similar, posts on the subject but I can't find anything that seems to lead me in the right direction of solving my problem.
I need to call the value of the variables from the watchPosition (and getCurrentPosition) method , set them as global and then call them inside of the function initMap().
The code is working but watchPosition reloads the Google map (this appears to happen when i change the browser/switch between tabs). I can't get the global variables to catch the value from the methods below (inside updateMarker).
How do I set the values from:
mon_lat = +position.coords.latitude;
mon_long = +position.coords.longitude;
to become global?
My main question is, more or less: how can i load the script without updating function initMap()? I would like it so that the navigator.geolocation.watchPosition() method updates automatically.
$(document).ready(function() {
updateMarker();
});
var mon_lat = null;
var mon_long = null;
var start_lat = null;
var start_long = null;
function updateMarker() {
// Get positions
if (navigator.geolocation) {
// Get current position
navigator.geolocation.watchPosition(
function (position) {
mon_lat = +position.coords.latitude;
mon_long = +position.coords.longitude;
initMap(mon_lat, mon_long);
}
);
// Get starting position
navigator.geolocation.getCurrentPosition(
function (position) {
start_lat = +position.coords.latitude;
start_long = +position.coords.longitude;
initMap(start_lat, start_long);
}
);
}
}
function initMap() {
// Display the map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: mon_lat, lng: mon_long},
zoom: 10,
mapTypeControl:false
});
}
I have an Yandex Maps installed on my project
Code below display an cluster view of all objects.
What I would like to do is disable clusters
$.getJSON( ymFormAction , "ymJSON=1" ).done( function (json) {
window.geoObjects = ymaps.geoQuery(json);
window.clusters = geoObjects.search("geometry.type == 'Point'").clusterize({preset: 'islands#invertedblueClusterIcons'});
myMap[[+idMap]].geoObjects.add(clusters);
// Trying to disable clusters
var coords = geoObjects;
// coords should be = [[56.023, 36.988]] according to API
var myCollection = new ymaps.GeoObjectCollection();
for (var i = 0; i<coords.length; i++) {
myCollection.add(new ymaps.Placemark(coords[i]));
}
myMap[[+idMap]].geoObjects.add(myCollection);
});
The thing is that ymaps.geoQuery doesn't return coordinates (or a GeoObjectCollection for that matter). What it returns is GeoQueryResult. Here what you can do to add results of geoQuery to a map:
ymaps.geoQuery(json).search("geometry.type == 'Point'").addToMap(yourMap);
The Setup
Currently building my phone gap iOS app which includes geolocation in addition to sending the results to a database and getting back nearby locations. Because I am using jQuery Mobile and Phonegap, I was testing on a browser to perfection, geolocation was success and everything returned was as well. On the iOS device, not so much. When sending a set latitude and longitude, everything returned successfully, but when using the google maps geolocation, and eventually the cordova plugin for geolocation, both failed as unable to find my location, even though they are the exact same code, minus the phone gap initializer on the website.
The Code
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
//Load Google Map & Geolocate
$(document).on("pagecreate", "#game", function () {
// keep as separate function call to allow for DOM to update after a tag
loadGoogleMap();
});
function loadGoogleMap() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); //default location is Hollywood, CA
if (navigator.geolocation) {
function success(pos) {
//set fields for current user latitude and longitude
$("#lat_in").val(pos.coords.latitude);
$("#lon_in").val(pos.coords.longitude);
//location found
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
//try cordova geolocation plugin
function onSuccess(position) {
alert("CDV position success");
//alert(position.coords.latitude);
//alert(position.coords.longitude);
}
function onError(error) {
alert("CDV position error");
//alert("code: " + error.code + "\n" + "message: " + error.message);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert("CDV position fail. Google geolocate fail"); //WHERE THE ERROR IS THROWN. THIS IS ALWAYS THE OUTCOME
//drawMap(defaultLatLng); //Failed to find location. Show default location
}
//Geolocate. Cache location for 5 mins. Timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {
maximumAge: 500000,
enableHighAccuracy: true,
timeout: 6000
});
} else {
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng) {
//Collect Data to Send
var uname = $("#unm_in").val();
var lat = $("#lat_in").val();
var lon = $("#lon_in").val();
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//update latitude and longitude on DB for logged in user && get nearby users
$.post("PHP_ON_SERVER", {
uname: uname,
lat: lat,
lon: lon
}, function (data) {
$.each(data, function (key, value) {
//Define variables
var allUsrLoc = new google.maps.LatLng(value.lat, value.lon);
var contentString = value.uname;
var mkrImg = "inUsrIcon.png"; //icon for logged in user
var inUserName = value.fname + " " + value.lname;
//if info belongs to current user
if (contentString === uname) {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player",
icon: mkrImg
});
//change header to name and points
$("#inUserInfo").text("Hi " + inUserName + " || You have " + value.points + " points");
//disable tag button if not it
if (value.isit === "notit") {
$("#tagBtn").addClass("ui-state-disabled");
}
}
//if not current user and is not it
else if (contentString != uname && value.isit != "it") {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player"
});
google.maps.event.addListener(marker, 'click', function () {
//Change selected player hidden field to match marker
$("#unm_sel").val(contentString);
$("#lat_sel").val(value.lat);
$("#lon_sel").val(value.lon);
$("#isit_sel").val(value.isit);
//Change tag button to selected player's username
$("#tagBtn").text("Tag " + contentString);
});
}
//no condition for if not current user and is it. TBD if anything will come
});
}, "json");
} //end drawMap
} // end loadGoogleMap
}
HTML
<div data-role="content" role="main" id="map-canvas">
<!-- Map loads here -->
</div>
Some More to Know
I have been reading up on other related questions, but none of the others do work. Either they say use the plugin, which I am to no avail, or set <access origin="*" /> which I am doing already. In addition, most of the other questions revolve around pre-3.0.0 versions of phone gap, which was its own monster. Also, the map loads, just no markers display. On the DB, the user who's location is being updated is set to (0,0). Lastly, when using geolocation in any other app, the iOS device I test on is successfully finding my location. In addition, I am testing on the same WiFi network as the browser which worked, so anything relating to internally being unable to locate due to network or hardware is ruled out.
If you want to see the working example, just ask.
I am using JQPlot trying to draw a graph which contains dates. But I cant able to draw the graph, but i tried the sample application it is working fine. But whenever i pass my array it is not working, can anyone please help what i am doing wrong? Below is the code i am using.
$.get("${contextPath}/qos/graphJQPlot", $("#qosForm").serialize()).done(function(content) {
$.each(content, function (index1, value1) {
var innerArray = [];
$.each(value1, function (index2, value2) {
innerArray.push(value2, index2);
console.log(index2);
console.log(value2);
})
outerArray.push(innerArray);
})
var line1=[['2008-09-30 4:00PM',4], ['2008-10-30 4:00PM',6.5], ['2008-11-30 4:00PM',5.7], ['2008-12-30 4:00PM',9], ['2009-01-30 4:00PM',8.2]];
var plot3 = $.jqplot('chartdiv', [outerArray],
{
title:'Line Style Options',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{formatString:'%b %#d, %y'}/* ,
min:'2013-09-14',
max:'2013-09-21',
tickInterval:'1 day' */
/* ,
tickOptions:{formatString:'%b %#d, %Y'},
*/
}
}
}
);
});
If i pause an line1 to jqPlot it is working fine, but if i pass an outerArray it is not working.
Don't forget to include jqplot.dateAxisRenderer.js plugins
I know there are a few topics on this, but I seem to be fumbling my way through with no results. I'm trying to use a controller to return JSON results to my Bing Maps functions.
Here's what I have for my controller (yes it is properly returning JSON data.
Function Regions() As JsonResult
Dim rj As New List(Of RtnJson)()
rj.Add(New RtnJson("135 Bow Meadows Drive, Cochrane, Alberta", "desc", "title"))
rj.Add(New RtnJson("12 Bowridge Dr NW, Calgary, Alberta, Canada", "desc2", "title2"))
Return Json(rj, JsonRequestBehavior.AllowGet)
End Function
Then in my script I have this, but it's not working.
<script type="text/javascript">
var map = null;
var centerLat = 51.045 ;
var centerLon = -114.05722;
var path = "<%: Url.Action("GetRegions", "Regions")%>";
function LoadMap() {
map = new VEMap('bingMap');
map.LoadMap(new VELatLong(centerLat, centerLon), 10);
$.getJSON(path, function(json){
$.each(json, function(){
alert(this.address); // the alert message is "undefined"
StartGeocoding(this.address, this.title, this.description);
});
});
}
function StartGeocoding(address, title, desc) {
map.Find(null, // what
address, // where
null, // VEFindType (always VEFindType.Businesses)
null, // VEShapeLayer (base by default)
null, // start index for results (0 by default)
null, // max number of results (default is 10)
null, // show results? (default is true)
null, // create pushpin for what results? (ignored since what is null)
true, // use default disambiguation? (default is true)
false, // set best map view? (default is true)
GeocodeCallback); // call back function
}
function GeocodeCallback(shapeLayer, findResults, places, moreResults, errorMsg) {
var bestPlace = places[0];
// Add pushpin to the *best* place
var location = bestPlace.LatLong;
var newShape = new VEShape(VEShapeType.Pushpin, location);
var desc = "Latitude: " + location.Latitude + "<br>Longitude:" + location.Longitude;
newShape.SetDescription(desc);
newShape.SetTitle(bestPlace.Name);
map.AddShape(newShape);
}
$(document).ready(function () {
LoadMap();
});
</script>
Well damn.
Turns out that I was using this.address when I should have been using this.Address. Can't believe I missed that.