Linking Geo server with osmdroid - osmdroid

I have been trying to get WMS Tiles from geo server on osmdroid. But so far no success. I just manage to get a tiny version of tiles geo server which locates at some other location. Yes the projection is right because i am using this same layer for my web application too.
Following is my code
MapTileProviderBasic tileProvider = new MapTileProviderBasic(getApplicationContext());
XYTileSource tilesource = new XYTileSource("tiger:tiger_roads",0, 18, 256, ".png", new String[]{"http://dev.propertyninja.com:8080/geoserver/gwc/service/tms/1.0.0"}) {
#Override
public String getTileURLString(MapTile aTile) {
return getBaseUrl() +"/tiger:tiger_roads/"+aTile.getZoomLevel()+"/"+aTile.getY()+"/"+aTile.getX()+".png";
}
};
tileProvider.setTileSource(tilesource);
TilesOverlay tilesOverlay = new TilesOverlay(tileProvider, this);
tilesOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);
map.getOverlays().add(tilesOverlay);
map.invalidate();
}
My logcat produces this as I keep on zooming in.
W/OsmDroid: Problem downloading MapTile: /9/147/193 HTTP response: Not Found

Your server has 4 different URLs for that layer:
<TileMap title="Manhattan (NY) roads" srs="EPSG:4326" profile="global-geodetic" href="http://dev.propertyninja.com:8080/geoserver/gwc/service/tms/1.0.0/tiger%3Atiger_roads#EPSG%3A4326#png"/>
<TileMap title="Manhattan (NY) roads" srs="EPSG:4326" profile="global-geodetic" href="http://dev.propertyninja.com:8080/geoserver/gwc/service/tms/1.0.0/tiger%3Atiger_roads#EPSG%3A4326#jpeg"/>
<TileMap title="Manhattan (NY) roads" srs="EPSG:900913" profile="global-mercator" href="http://dev.propertyninja.com:8080/geoserver/gwc/service/tms/1.0.0/tiger%3Atiger_roads#EPSG%3A900913#png"/>
<TileMap title="Manhattan (NY) roads" srs="EPSG:900913" profile="global-mercator" href="http://dev.propertyninja.com:8080/geoserver/gwc/service/tms/1.0.0/tiger%3Atiger_roads#EPSG%3A900913#jpeg"/>
The fact that your tiles end up being too small suggests that you are using ESPG:4326 (latlon) instead of Google Web Mercator (EPSG:900913).
There is also the issue that you are using an XYZTileSource for a TMS layer - so there is a fair chance that the Y coordinate is flipped.

Related

Offline Maps HERE-SDK - offline search and navigation

I am using HERE-Android-SDK to build a simple navigation solution with offline maps.
While using the offline mode for the search addresses and calculation of a route, I can see that there are results returned from the address-search, which are not included in the installed offline map datasets. Is there anything additional which I need to do, in order to get only search results which are located inside the offline-map data installed on my device?
I am using the following code snippets.
download offline maps for a specific country:
mapsLoader.selectDataGroup(MapPackage.SelectableDataGroup.TruckAttributes)
mapsLoader.installMapPackages(listOf(mapPackageId))
search request for addresses:
val term = "New York"
val center = GeoCoordinate(lastWayPoint.latitude, lastWayPoint.longitude)
val request = SearchRequest(term)
request.connectivity = Request.Connectivity.OFFLINE
request.locale = Locale.GERMAN
request.setSearchCenter(center)
request.collectionSize = 5
request.execute { data, error ->
if (error != ErrorCode.NONE) return
// handle search results here
}
Thanks for all of your help in advance!

Ionic 2 / cordova-plugin-file File.writeFile() refuses to create binary file correctly (png image)

In summary
File.writeFile() creates a PNG file of 0 bytes when trying to write a Blob made from base64 data.
In my application, I am trying to create a file that consists of base64 data stored in the db. The rendered equivalent of the data is a small anti-aliased graph curve in black on a transparent background (never more that 300 x 320 pixels) that has previously been created and stored from a canvas element. I have independently verified that the stored base64 data is indeed correct by rendering it at one of various base64 encoders/decoders available online.
Output from "Ionic Info"
--------------------------------
Your system information:
Cordova CLI: 6.3.1
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.39
OS:
Node Version: v6.7.0
--------------------------------
The development platform is Windows 10, and I've been testing directly on a Samsung Galaxy S7 and S4 so far.
I know that the base64 data has to be converted into binary data (as a Blob) first, as File does not yet support writing base64 directly in to an image file. I found various techniques with which to do this, and the code which seems to suit my needs the most (and reflects a similar way I would have done it in java is illustrated below):
Main code from constructor:
this.platform.ready().then(() => {
this.graphDataService.getDataItem(this.job.id).then((data) =>{
console.log("getpic:");
let imgWithMeta = data.split(",")
// base64 data
let imgData = imgWithMeta[1].trim();
// content type
let imgType = imgWithMeta[0].trim().split(";")[0].split(":")[1];
console.log("imgData:",imgData);
console.log("imgMeta:",imgType);
console.log("aftergetpic:");
// this.fs is correctly set to cordova.file.externalDataDirectory
let folderpath = this.fs;
let filename = "dotd_test.png";
File.resolveLocalFilesystemUrl(this.fs).then( (dirEntry) => {
console.log("resolved dir with:", dirEntry);
this.savebase64AsImageFile(dirEntry.nativeURL,filename,imgData,imgType);
});
});
});
Helper to convert base64 to Blob:
// convert base64 to Blob
b64toBlob(b64Data, contentType, sliceSize) {
//console.log("data packet:",b64Data);
//console.log("content type:",contentType);
//console.log("slice size:",sliceSize);
let byteCharacters = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
console.log("size of bytearray before blobbing:", byteArrays.length);
console.log("blob content type:", contentType);
let blob = new Blob(byteArrays, {type: contentType});
// alternative way WITHOUT chunking the base64 data
// let blob = new Blob([atob(b64Data)], {type: contentType});
return blob;
}
save the image with File.writeFile()
// save the image with File.writeFile()
savebase64AsImageFile(folderpath,filename,content,contentType){
// Convert the base64 string in a Blob
let data:Blob = this.b64toBlob(content,contentType,512);
console.log("file location attempt is:",folderpath + filename);
File.writeFile(
folderpath,
filename,
data,
{replace: true}
).then(
_ => console.log("write complete")
).catch(
err => console.log("file create failed:",err);
);
}
I have tried dozens of different decoding techniques, but the effect is the same. However, if I hardcode simple text data into the writeFile() section, like so:
File.writeFile(
folderpath,
"test.txt",
"the quick brown fox jumps over the lazy dog",
{replace: true}
)
A text file IS created correctly in the expected location with the text string above in it.
However, I've noticed that whether the file is the 0 bytes PNG, or the working text file above, in both cases the ".then()" consequence clause of the File Promise never fires.
Additionally, I swapped the above method and used the Ionic 2 native Base64-To-Gallery library to create the images, which worked without a problem. However, having the images in the user's picture gallery or camera roll is not an option for me as I do not wish to risk a user's own pictures while marshalling / packing / transmitting / deleting the data-rendered images. The images should be created and managed as part of the app.
User marcus-robinson seems to have experienced a similar issue outlined here, but it was across all file types, and not just binary types as seems to be the case here. Also, the issue seems to have been closed:
https://github.com/driftyco/ionic/issues/5638
Anybody experiencing something similar, or possibly spot some error I might have caused? I've tried dozens of alternatives but none seem to work.
I had similar behaviour saving media files which worked perfectly on iOS. Nonetheless, I had the issue of 0 bytes file creation on some Android devices in release build (dev build works perfectly). After very long search, I followed the following solution
I moved the polyfills.js script tag to the top of the index.html in the ionic project before the cordova.js tag. This re-ordering somehow the issue is resolved.
So the order should look like:
<script src="build/polyfills.js"></script>
<script type="text/javascript" src="cordova.js"></script>
Works on ionic 3 and ionic 4.
The credits go to 1
I got that working with most of your code:
this.file.writeFile(this.file.cacheDirectory, "currentCached.jpeg", this.b64toBlob(src, "image/jpg", 512) ,{replace: true})
The only difference i had was:
let byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
instead of your
let byteCharacters = atob(b64Data);
Note: I did not use other trimming etc. like those techniques you used in your constructor class.

Parsing XML webservice and storing the data for presentation on a windows phone 7 device

I'm working on an app that requires extracting data from an xml web service, then I want to store that data (images+titles+datetime ...) to display it on my app then select an item and navigate to another page that displays more info about this item.
Is there a detailed tutorial that explains the parsing and storing process clearly (with the threads) because I'm gonna need it a lot for my app.Thanks!
I usually use this method, but didn't always get me what i want:
var doc = XDocument.Load(new StringReader(e.Result));
var items = from c in doc.Descendants("item")
select new RSSitem()
{
Title = c.Element("title").Value,
Photo = c.Element("img").Attribute("src").Value,
Description = c.Element("description").Value,
Link = c.Element("link").Value,
};
ListBoxNews.ItemsSource = items;
Sounds like you are in over your head (based on the vague nature of your question). So I'm offering my advise to get up to speed, so you can get started and ask a question that we can help give a definitive answer to.
With WP7 and .NET you shouldn't really have to do much manual parsing of Web Services. You should be able to add a Service Reference and generate a proxy which will handle this for you. This will also generate business objects for the data returned by your service.
Once you have that done, you can look into Windows Phone Navigation which should help you transition between pages in your application.
To consume web services:
String baseUri = “your service URI";
WebClient wc = new WebClient();
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_downloadstringcompleted);
// event handler that will handle the ‘downloadstringsompleted’ event
wc.DownloadStringAsync(new Uri(baseUri));
// this method will download your string URI asynchronously
}
void wc_downloadstringcompleted(Object sender, DownloadStringCompletedEventArgs e)
{
// method will get fired after URI download completes
// writes your every code here
}
To parse the data:
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
break;
case XmlNodeType.EndElement:
break;
}
}
}
}
To store in isolated storage: http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings%28v=vs.95%29.aspx
For navigation:
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + navigationstring, UriKind.Relative));

How to get large photo URL in one API call?

I want to display large photos in my Facebook app's feed view immediately. Is it possible to get the large photo src URL from a stream/feed using one API call? The photo id is returned in the stream/feed and one can of course then supply this photo id in an additional FQL or graph API call to retrieve all the information about that photo. However, is there a way using multi-query or batch calls to get a larger photo src url using one API roundtrip?
I haven't tried this with stream/feed photos, but the generally accepted way of doing this is:
http://graph.facebook.com/{ID of object}/picture
If you want the "large" version, you would do:
http://graph.facebook.com/{ID of object}/picture?type=large
I'm not 100% sure if this would work for an actual photo (instead of a user profile picture or page profile pic), but I have a hunch it will - the only caveat is that you obviously must have a logged in user that is authorized to view the photo (unless it's public).
If anybody is looking to this and type large is not enough, I found other solutions.
Type large is kind of small anyway (close to 200px). You can get larger image by adding i.e. ?width=1000 or ?height=1000. Facebook will return picture closest to given dimension and preserve aspect ratio. When passing both dimenstions like ?width=1000&height=1000, facebook will cut image to given dimensions (in this case square).
Use Facebook UserId (Oject ID) to get the picture.
https://graph.facebook.com/173xxxx8635/picture?type=large&redirect=false
which returns JSON data with picture URL.
{
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/xxx/xyz/1cc066a2cae3f301d"
}
}
A good trick with the new api is to get the pic_cover field from the event table and to process it according to the size you want to use
I found when I was having this trouble that it turned out to be the picture I was downloading rather than the size I was setting it.
If for example I downloaded all my photos with a request of
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,picture&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"picture"]
}
}];
I am using the dictionary key search "picture" as I want the picture.
This though will get me a lower quality picture than if I searched for "source" in this search:
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,source&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"source"]
}
}];
If you go on the Facebook API explorer and search for photos and then click on the picture and source jpg links you can see the difference in size and quality.
Since changing this method I have managed to get rid of using the type parameters as it doesn't seem to make a different.
Note: I am using iPhone and not iPad or a larger screen so I don't know how this affects bigger screens.
The answer by #streetlogics works fine but only on pictures that have {object_id}.
http://graph.facebook.com/{object_id}/picture
But I also wanted large pictures for the feed's shared links, which sometimes don't have {object_id}. I finally realized that the {picture} thumbnail URL contains the encoded URL for the original site's large image:
https://external.xx.fbcdn.net/safe_image.php?d=AQBe9UvGd0vPbAHP&w=130&h=130&url=http%3A%2F%2Fskift.com%2Fwp-content%2Fuploads%2F2015%2F12%2Fpollution.jpg&cfs=1
--> contains -->
http://skift.com/wp-content/uploads/2015/12/pollution.jpg
So I made a loop that checks for {object_id} and if not present then extracts the URL from {picture}:
if(isset($post['object_id'])) {
echo "http://graph.facebook.com/".$post['object_id']."/picture";
}
elseif(isset($post['picture'])) {
echo urldecode(preg_replace('/&cfs.*/', '', preg_replace('/.*url=/', '', $post['picture'])));
}
else {
echo "no_large_image";
}

Sitecore Clear Cache Programmatically

I am trying to publish programmatically in Sitecore. Publishing works fine. But doing so programmatically doesn't clear the sitecore cache. What is the best way to clear the cache programmatically?
I am trying to use the webservice that comes with the staging module. But I am getting a Bad request exception(Exception: The remote server returned an unexpected response: (400) Bad Request.). I tried to increase the service receivetimeout and sendtimeout on the client side config file but that didn't fix the problem. Any pointers would be greatly appreciated?
I am using the following code:
CacheClearService.StagingWebServiceSoapClient client = new CacheClearService.StagingWebServiceSoapClient();
CacheClearService.StagingCredentials credentials = new CacheClearService.StagingCredentials();
credentials.Username = "sitecore\adminuser";
credentials.Password = "***********";
credentials.isEncrypted = false;
bool s = client.ClearCache(true, dt, credentials);
I am using following code to do publish.
Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Database web = Sitecore.Configuration.Factory.GetDatabase("web");
string userName = "default\adminuser";
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
user.RuntimeSettings.IsAdministrator = true;
using (new Sitecore.Security.Accounts.UserSwitcher(user))
{
Sitecore.Publishing.PublishOptions options = new Sitecore.Publishing.PublishOptions(master, web,
Sitecore.Publishing.PublishMode.Full, Sitecore.Data.Managers.LanguageManager.DefaultLanguage, DateTime.Now);
options.RootItem = master.Items["/sitecore/content/"];
options.Deep = true;
options.CompareRevisions = true;
options.RepublishAll = true;
options.FromDate = DateTime.Now.AddMonths(-1);
Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(options);
publisher.Publish();
}
In Sitecore 6, the CacheManager class has a static method that will clear all caches. The ClearAll() method is obsolete.
Sitecore.Caching.CacheManager.ClearAllCaches();
Just a quick note, in Sitecore 6.3, that is not needed anymore. Caches are being cleared automatically after a change happens on a remote server.
Also, if you are on previous releases, instead of clearing all caches, you can do partial cache clearing.
There is a free shared source component called Stager that does that.
http://trac.sitecore.net/SitecoreStager
If you need a custom solution, you can simply extract the source code from there.
I got this from Sitecore support. It clears all caches:
Sitecore.Context.Database = this.WebContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Context.ClientData.RemoveAll();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.Database = this.ShellContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.ClientData.RemoveAll();
Out of the box solution provided by Sitecore to clean caches (ALL of them) is utilized by the following page: http://sitecore_instance_here/sitecore/admin/cache.aspx and code behind looks like the following snippet:
foreach (var cache in Sitecore.Caching.CacheManager.GetAllCaches())
cache.Clear();
Via the SDN:
HtmlCache cache = CacheManager.GetHtmlCache(Context.Site);
if (cache != null) {
cache.Clear();
}