How can I publish vector layers with Leaflet? - javascript

I am trying to publish my vector layers in geoserver as WFS using the Leaflet library and I get the error like in the picture. How can I fix this error and is there any other way to publish WFS with leaflet?
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src=" https://unpkg.com/leaflet#1.2.0/dist/leaflet.js "></script>
<link rel="stylesheet" href=" https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js" ></script>
<style>
#map {
width: 100%;
height: 600px;
box-shadow: 5px 5px 5px #888;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([0, 0], 2);
var owsrootUrl = 'http://localhost:8080/geoserver/ows?';
var defaultParameters = {
service: 'WFS',
version: '1.1.0',
request: 'GetFeature',
typeName: 'webalani:il',
outputFormat: 'application/json',
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
$.ajax({
url: URL,
success: function (data) {
var geojson = new L.geoJson(data, {
style: {"color":"#2ECCFA","weight":2},
}
).addTo(map);
}
});
</script>
</body>
</html>

You are attempting to run your leaflet file directly by double clicking on the file location on your disk. This will not work as the AJAX methods you are using require a web server to be used instead.
Make sure you are looking at http://localhost.... not file://..... in your browser bar and all will be well.

Related

handling multiple chat boxes in ajax jquery

i am planning to implement chat application using ajax, java script in front and java rest api in back . everything is going well, but whenever i try to open multiple chat boxes to chat with multiple user. i am struggling to create different chat boxes associated with different users. my entire front-end code is below . Can somebody please help me? thanks in advance...
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat Application</title>
<style>
.userListDiv{
border:1px solid blue;
overflow: auto;
width:500px;
}
#messageBox{
border:2px solid black;
overflow: auto;
height:auto;
width:300px;
}
#messageInput{
size:100px;
border:1px solid black;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway'
rel='stylesheet' type='text/css'>
<link rel="stylesheet"
href="//cdn.jsdelivr.net/jquery.sidr/2.2.1/stylesheets/jquery.sidr.light.min.css">
</head>
<body>
<button id='myId' value =userId></button>
<div class="userListDiv"></div>
<div class ="chatbox">
<div id ="messageBox">
</div>
</div>
<script>
var baseUrl="http://localhost:8080/sampleHospital/webapi/";
$(document).ready(function(){
$('#myId').hide();
$('.chatbox').hide();
var timeOut = 1000;
$.ajax({
url: baseUrl+"users",
method:"GET",
datatype:"xml",
success:getUsers,
error: function(xhr,ajaxOption,thrownError){
console.log(xhr.status);
console.log(thrownError);
}
}, timeOut);
});
function sendMessage(senderId,recieverId){
var Inputmessage= $('.messageInput').val();
var message = $.parseXML('<message><date></date><id></id><senderID></senderID><recieverID></recieverID><content></content></message>');
var $messageXml = $(message);
$messageXml.find('content').append(Inputmessage);
$messageXml.find('senderID').append(senderId);
$messageXml.find('recieverID').append(recieverId);
console.log(message);
$('.messageInput').val="";
$.ajax({
url: baseUrl+"messages/",
type:"POST",
dataType:'xml',
data:message,
processData:false,
contentType:"application/xml",
success: getMessage,
error: function(xhr){
console.log(xhr.status);
console.log("error!!!");
}
});
}
function requestMessage(senderID, recieverID){
var timeInterval = 1000;
$(".chatbox").fadeIn(500);
$(".chatbox").append("<div id ='chatContainer'></div>");
$('.chatbox').append('<input type="text" class="messageInput" placeHolder="your message here"/><button class="sendMessage" onclick="sendMessage(1,2)">send message</button>');
$.ajax({
url:baseUrl +"messages/"+senderID +"/"+ recieverID,
method:"GET",
datatype:"xml",
success :getMessage,
error: function(xhr ,ajaxOptions,thrownError){
console.log(xhr.status);
console.log(thrownError);
}
}, timeInterval);
}
function getMessage(data,status){
console.log("getting messages");
console.log(data);
var messageBox =$("#messageBox") ;
messageBox.empty();
messageBox.append($('<ul id ="messagesList"></ul>'));
$(data).find('message').each(function(){
var message = $(this).find('content').text();
var date = $(this).find('date').text();
var sender = $(this).find('senderID').text();
var receiver = $(this).find('recieverID').text();
console.log(message);
$("#messagesList").append('<li>'+message+'</li>');
});
}
function getUsers(data,status){
console.log("getting users list");
console.log(data);
var userListBox = $(".userListDiv");
userListBox.empty();
userListBox.append('<ul class="usersList"></ul>');
$(data).find('user').each(function(){
var name = $(this).find('fullName').text();
var otherid = $(this).find('id').text();
var myId =2;
// console.log(name,otherid);
$('.usersList').append('<li class='+name+' onclick="requestMessage(1,2)"><a href="javaScript:void(0)">'+name+'</li>');
});
}
</script>
</body>
</html>
in the request message you are trying to create chatcontainer div. For any user you are using same div id so you wont be able to update the values properly. You should create the id uniquely may be appending with receiver id. More over if div with that id is there then you should not create it again. you should use the existing div and update the messages.

jQuery, ajax, and php web scraper acting strangely

I'm trying to scrape a web page, but getting some weird results in my browser's console (as seen below). Here's my code:
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icefilms Searcher</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>
script.js
$(document).ready(function(){
var currNum = 168000;
var maxNum = 168005;
function generateNextUrl(){
currNum++;
return currNum-1;
}
scrapeThis(generateNextUrl());
function scrapeThis(theUrl){
$.ajax({
url:
"php.php",
data:
"icefilmsURL=" + theUrl,
success:
function(response){
var movieTitle = $(response).find("#videotitle").find("span:first").text();
$("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
},
complete:
function(){
if(currNum < maxNum+1){
scrapeThis(generateNextUrl());
}
},
error:
function(xhr,err){
$("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
$("#container").append("responseText: "+xhr.responseText);
}
});
};
});
php.php
<?php
echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>
The code works fine, but this is what I see in my console:
Any ideas?
You are seeing those in the console because the page you are scraping contains references to relative paths.
That is to say rather than
<img src="http://www.icefilms.info/someimage.jpg">
The code is
<img src="someimage.jpg">
Therefore, when you grab and display their HTML on your own domain the browser is trying to load the image from your domain, localhost in this case. But you do not have the image on your server.
You can use a base href in the HTML to resolve this, or you could find and replace relative path images to include the domain.
<base href="http://www.icefilms.info/">

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

how to show google map and get coordinates on device through javascript code?

I did it in android but now i need to build app through phone-gap and i need to load map on the device and get current position coordinate(latitude and longitude) of the device.
So i need to have javascript code now and to be frank i am not much familiar with java script for now…Any code/help.
This is my code through which i am showing the map
Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key*****************&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
In the place of "*" i am having my google api key..
Now i need to get the coordinates…
modified and currently using this code got from the link http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html but even then i am getting this error "KCLErrorDomain Error 0"
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
function onDeviceReady() {
var options = { frequency: 5000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation">locating coordinates...</p>
</body>
</html>
I am not getting how to solve this error…using xcode 4.0.1 for phonegap apps development and trying to run on 4.3 simulator..
Here a quote from the PhoneGap documentation on Geolocation (http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html):
Geolocation provides location information for the device, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. No guarantee is given that the API returns the device's actual location.
This API is based on the W3C Geo location API Specification. Some devices already provide an implementation of this spec. For those devices, the built-in support is used instead of replacing it with PhoneGap's implementation. For devices that don't have geolocation support, PhoneGap's implementation should be compatible with the W3C specification.
So basically, you can use the HTML5 Geolocation API without having to worry about any differences in PhoneGap. If you want to get the user's position once, use navigator.geolocation.getCurrentPosition() and if you want to periodically be sent the user's position, use navigator.geolocation.watchPosition():
navigator.geolocation.watchPosition(locationSuccess, locationError, {timeout: 30000});
function locationSuccess(position)
{
// this is your position as a LatLng object. use it however you need
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}
function locationError(err)
{
if (err.code == 1)
alert("You must allow this website to use the Geolocation API to access your position.");
else if (err.code == 3)
alert("Unfortunately, your position request timed out.");
else
alert("Unfortunately, your position could not be determined.");
}

XMPP - Example chapter 3 "Professional XMPP Programming with JavaScript and jQuery" doens't work

I am just new to XMPP, and I am making the first "HELLO" code. Please take your time look at the following code (the .zip is at the end of this topic):
<html>
<head>
<title>Hello - Chapter 3</title>
<style type="text/css">
body {
font-family: Helvetica;
}
h1 {
text-align: center;
}
.hidden {
display: none;
}
#log {
padding: 10px;
}
</style>
<script language="javascript" type="text/javascript" src="scripts/jQuery.js"></script>
<script language="javascript" type="text/javascript" src="scripts/jQueryUI.js"></script>
<script language="javascript" type="text/javascript" src="scripts/strophe.js"></script>
<script language="javascript" type="text/javascript" src="scripts/flXHR.js"></script>
<script language="javascript" type="text/javascript" src="scripts/strophe.flxhr.js"></script>
<link rel="stylesheet" href="hello.css"></link>
<script language="javascript" type="text/javascript">
var Hello = {
connection: null,
log: function(msg) {
$("#log").append("<p>" + msg + "</p>");
}
};
$(document).ready(function() {
$("#login_dialog").dialog({
autoOpen: true,
draggable: false,
modal: true,
title: "Connect to XMPP",
buttons: {
"Connect": function() {
$(document).trigger("connect", {
jid: $("#jid").val(),
password: $("#password").val()
});
$("#password").val("");
$(this).dialog("close");
}
}
});
$(document).bind("connect", function(ev, data) {
var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function(status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger("connected");
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger("disconnected");
}
});
Hello.connection = conn;
});
$(document).bind("connected", function() {
// Inform the user
Hello.log("Connection established");
});
$(document).bind("disconnected", function() {
Hello.log("Connection terminated.");
// Remove dead connection object
Hello.connection = null;
});
});
</script>
</head>
<body>
<h1>Hello</h1>
<div id="log"></div>
<!-- Login dialog -->
<div id="login_dialog" class="hidden">
<label>JID:</label><input type="text" id="jid">
<label>Pwd:</label><input type="password" id="password">
</div>
</body>
</html>
According to the document, and the code, it must either say "Connection establised" or "Connection terminated". But it doesn't. I tried to put alert("It runs to here!"); in every line of the code, and it still alert(). It doesn't alert anymore when I put it in bind("connected") and bind("disconnect"). So I guess the code can not run to there. I've never done it before, and there is rarely documents about this, so I don't know what to do now.
Question: Could you guys please take a look at it, and tell me what was wrong? I myself is still working on debugging it!
Extra information: These are what is in my web folder (I am afraid of missing javascript framework files). All js files are latest version.
index.html
scripts/
jQuery.js
jQueryUI.js
strophe.js
flensed.js
flXHR.js
flXHR.swf
flXHR.vbs
swfobject.js
updateplayer.swf
checkplayer.js
css/
Not important...
Here are my code, please take time to view it: http://xx3004.kodingen.com/XMPP
I would appreciate any view of help.
[x]
your code is alright,
the problem is in the URL provided to make the connection using Strophe.
var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
Try to find the location of the server, otherwise install an xmpp server(vysper), locally on your machine, and change the URL as http://localhost:8080/bosh/
Also try to comment the flxhr inclusion.
If you are running Openfire on your localhost make sure
bosh_service_url = 'http://127.0.0.1:7070/http-bind/'
ie
var conn = new Strophe.Connection("http://127.0.0.1:7070/http-bind/");
And if you are running ejabberd on your localhost make sure
bosh_service_url = "http://127.0.0.1:5222/http-bind/"

Categories