leaflet maps add raster - javascript

i want to add a raster file in the leaflet map,after from searching i find this example where is that i need i think georaster-layer-for-leaflet-example.
the code look simple js :
var parse_georaster = require("georaster");
var GeoRasterLayer = require("georaster-layer-for-leaflet");
// initalize leaflet map
var map = L.map('map').setView([0, 0], 5);
// add OpenStreetMap basemap
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var url_to_geotiff_file = "example_4326.tif";
fetch(url_to_geotiff_file)
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
parse_georaster(arrayBuffer).then(georaster => {
console.log("georaster:", georaster);
/*
GeoRasterLayer is an extension of GridLayer,
which means can use GridLayer options like opacity.
Just make sure to include the georaster option!
http://leafletjs.com/reference-1.2.0.html#gridlayer
*/
var layer = new GeoRasterLayer({
georaster: georaster,
opacity: 0.7
});
layer.addTo(map);
map.fitBounds(layer.getBounds());
});
});
error :
GeoTIFF: Object
bundle.js:16 Fetch API cannot load file:///C:/Users/username/Downloads/georaster-layer-for-leaflet-example-master/example_4326.tif. URL scheme must be "http" or "https" for CORS request.
1.georaster # bundle.js:16
bundle.js:16 Uncaught (in promise) TypeError: Failed to fetch
at Object.1.georaster (bundle.js:16)
at s (bundle.js:1)
at e (bundle.js:1)
at bundle.js:1
any idea how to fix it ?

The error message is saying that the tiff should be hosted online: "URL scheme must be "http" or "https".
Try putting your tiff online somewhere such as on github or the server you plan to host your map, the on the line var url_to_geotiff_file = "example_4326.tif";, use the full URL for the tiff.

Faced the same issue!
Steps to solve the issue:
1) You can solve it by, publishing it on a local web server such as apache tomcat (by default your file URL will be something like: http://localhost:8080/file_name.tif).
2) Now if you will try to load the map georaster layer, you will get an error such as this:
Access to fetch at 'http://localhost:8080/file_name.tif' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
3) To solve the above problem add the extension Allow-Control-Allow-Origin to your chrome browser and enable it.
It will work then!

Related

Can't remove CORS error even so I included all headers

I am writing simple web-site with js-client and a server side(python) I did everything to remove CORS error but nothing works. I wrote all needed headers for this but still get this error. So web-site should send a request to a server and get answer.
Error:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
myFile.html:
<!DOCTYPE html>
<html>
<head>
<title>requestJs</title>
</head>
<body>
<button class="myButton">SEND</button>
<script type="text/javascript">
let theButton = document.querySelector(".myButton");
theButton.addEventListener('click',function() {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(`Статус: ${xhr.status}; Результат: ${xhr.response}`)
};
xhr.onerror = function() {
alert('Ошибка запроса');
};
xhr.open("GET", "http://127.0.0.1:8000/", true);
xhr.send(2);
})
</script>
</body>
</html>
Server side:
import http.server as httpserver
class CORSHTTPRequestHandler(httpserver.SimpleHTTPRequestHandler):
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.html":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Access-Control-Allow-Origin:", "*")
self.send_header("Access-Control-Allow-Methods:", "GET,HEAD,PUT,PATCH,POST,DELETE")
self.send_header("Access-Control-Allow-Headers:", "Content-Type, Access-Control-Allow-Origin, xxx")
self.end_headers()
return f
if __name__ == "__main__":
import os
import socketserver
import sys
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
handler = CORSHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print(f"serving at port {PORT}")
httpd.serve_forever()
Help me please, what is my problem?
This is not a comprehensive answer but it might help.
CORS is entirely a browser feature. You can turn it off in your browser. I suggest the first step therefore is to launch a CORS-free browser to test your app. Make sure not to open your banking page in this browser session though, it isn't safe!
google-chrome --user-data-dir=/var/tmp/Chrome --disable-web-security
If everything works then then issue is just CORS.
If you are only running in a dev environment, you can just do this everytime even.
If you are running in production, the easiest option is often just to use a gateway that fixes this stuff for you. That's how I got mine working.
If the above isn't good enough and you want to debug, remember that all browser CORS requests are initiated by a preflight OPTIONS requests. Sometimes that's where the problem comes in. Make sure your server is able to handle and respond to OPTIONS, and check that it is responding correctly.

Bad XMLHttpRequest when uploading to S3

I'm using Evaporate.js to upload files to S3. I've had everything working, until I decided to enable server side encryption.
According to the S3 docs, you can enable it by passing a header. So I updated my add code to look like:
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
xAmzHeadersAtInitiate: { 'x-amz-server-side​-encryption': 'AES256'} // THIS IS THE ONLY LINE THAT CHANGED!!!
}
)
I get the error: DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'AWS4-HMAC-SHA256 Credential=XXXXXXXXXXXXXXX/XXXXXXX/us-east-1/s3/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-server-side​-encryption, Signature=XXXXXXXXXXXXXXXXXXXXX' is not a valid HTTP header field value.
Update:
Header fields can only be ASCII characters. x-amz-server-side-encryption in your code contains a hidden character. Type it instead of copy pasting it from somewhere. Go to this web page and paste the header field name after copying from your question, you will see what i mean.
From the documentation:
You can't enforce whether or not objects are encrypted with SSE-S3 when they are uploaded using pre-signed URLs.
You need to sign the header along with the URL. Just sending the headers after signing the URL won't work.
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
signHeaders: { 'x-amz-server-side-encryption': 'AES256' }, // notice this
xAmzHeadersAtInitiate: { 'x-amz-server-side-encryption': 'AES256'} // this should be fine now as we have the header in the signed request too but try removing this if you still get an error. S3 does not require you to re-specify the headers that were already signed.
});

AngularJS and Web API :- net::ERR_CONNECTION_REFUSED in chrome and error 00002efd in IE

There are lots of question like my question but I didn't any working solution.
I am using AngularJS and WebApi2 in my application.
Here is the JS code which call the initial API.
(function (module) {
var baseUrl= "http://localhost:85";
module.constant('Config', baseUrl);
module.service('identities', ['$http', function ($http) {
var uri = baseUrl+ '/api/controller/GetRole';
var identities = {};
identities.get = function () {
var temp = $http.get(uri);
console.log(temp, "identities");
return temp;
}
return identities;
}]);
This function call the GetRole method in web API controller to retrieve user role.The output of this method is JSON with user details.
I have deployed the application on a server to port 85. When I run the application it's throwing error in Chrome:
net::ERR_CONNECTION_REFUSED
and in IE 11:
XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd
There is no log created in IIS for this request.
Using fiddler I got this in Raw with status code 502 in response.
The connection to 'localhost' failed.
Error: ConnectionRefused (0x274d).
System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:85.
I have also tried by disabling the CORS in chrome but no luck.
IF I use IP address of server instead of localhost as baseUrl in angular JS code then it's working fine.
Why it's not working with localhost?
I am doing a GET call and Error for me is 00002efd not 00002ef3.

My maplabels stopped working. I now get the message below in all my programs

new MapLabel used to work in all my programs but this does not work any more:
var mapLabelA = new MapLabel(
{
text: ' From Wilkes or Henlow** ',
position: new google.maps.LatLng(49.796600, -97.196000),
map: map,
fontSize: 13,
align: 'right'
}
);
Why would my maplabels stop working?
Failed to load resource: the server responded with a status of 404 (Not Found)
PT59AM2.html:1039 Uncaught ReferenceError: MapLabel is not defined
util.js:222 Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
util.js:222 Google Maps API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key
Google deleted maplabel.js from their servers. Find another copy or link to it locally.

Angularjs Error in loading external jsonfile from server

I am trying to load json file from server .Here is my services.js file
angular.module('starter.services', [])
/**
* A simple example service that returns some data.
*/
.factory('Friends', function($http) {
var friends;
//here is the code for server access
$http.get('http://wwww.root5solutions.com/ionictest/get.json').then(function(msg){
console.log("console output"+msg.data);
friends=msg.data;
console.log("from server"+friends.data);
});
return {
all: function() {
return friends;
},
get: function(friendId) {
return friends[friendId];
}
}
});
But its not worked properly.Here is my console message
XMLHttpRequest cannot load http://www.root5solutions.com/ionictest/get.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have also faced the same problem.I am sure it will resolve your problem,
For Windows... create a Chrome shortcut on your desktop > Right-clic > properties > Shortcut > Edit "target" path : > "C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
NOTE: After setting this exit from chrome and then open
you have to whitelist that URL
try this
.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our other assets domain. Note there is a difference between * and **.
'http://wwww.root5solutions.com/ionictest/**',
]);
})
All this problem beacuse i tested only using browser.When tesing on device/emulator its working perfect.There is no need of additional coding to overcome this problem.

Categories

Resources