Static route image showing broken (Google Maps Directions API) - image

I'm attempting to retrieve a static image of a route from Google Maps directions API.
// addresses
$from_address = "Mobile,AL"
$to_address = "Athens,GA"
// build static image url
$url_route_json = "https://maps.googleapis.com/maps/api/directions/json?origin=$from_address&destination=$to_address&mode=driving&key=$goog_map_dist_api_key";
// replace any spaces in the route address with + signs
$url_route_json = str_replace(' ', '+', $url_route_json);
// get the json response
$resp_json = file_get_contents($url_route_json);
// decode the json
$jsondata = json_decode($resp_json, true);
// URL encode overview_polyline
$overview_polyline = urlencode($jsondata['routes'][0]['overview_polyline']['points']);
// build image URL
$url_route_img = "https://maps.googleapis.com/maps/api/staticmap?size=600x400&path=enc%3A$overview_polyline&key=$goog_map_dist_api_key";
url_route_img becomes:
https://maps.googleapis.com/maps/api/staticmap?size=600x400&path=enc:wknnEvj%7B%7DN%7CA%60DYRgDxBZx%40hArC%60A%7CBtEtKzEfLrBhF%7E%40dD%7CGtRJ%5CrD_Bh%40K%60%40FjAbBVZJJXk%40d%40%7D%40Zm%40f%40y%40%7C%40eAtK%7BHtGoEv%40i%40HDP%40pAWvABjGn%40%7CGp%40%60F%60%40zMrAfEf%40pCf%40lEzAhCrAtMtIvBnAzB%60A%7EBt%40%7EJzBtOpDbFnAdK%60ClEz%40nOnDlCh%40bDZhDB%7CCSbCc%40j%40Oj%40N%7EEr%40jA%60%40%7E%40x%40%60LzM%60C%7CBn%40RfBN%7CBJhFj%40vD%60%40jB%5ChBbAfB%7EBpFjTpBlH%60%40%7C%40t%40%7E%40vCtBl%40j%40FXBTB%60%40iD%7EOwJdd%40%7BLxj%40sB%7CHkBvFoC%60HoC%7EFwX%7Ej%40gD%60IoCfIqCrKsBpJwNhq%40mOds%40%7DYxtAmM%60m%40iArFgBpK_BnMiCdYaFxh%40oJ%7EcAsGpr%40cC%60XsCj%5By%40bQQnIChJWnx%40e%40riB%7D%40faDIxXU%7CE%7B%40rGaA%7EDsAxDcBjDuB%7ECcCjCiYhXgMlNeFvGmChDmCnFuBpG%7DAtHkA%60K%5B%60HEdDFjFNrDf%40nFt%40dF%7EAhH%7EF%7CUv%40%7EE%5C%7EDb%40zWLvJRvNj%40bOhA%7CNpAxLfBpOlDr%5BzEfc%40lQn_BtFlg%40%60BrMb%40xBr%40dCfArCjGxJxEvHjG%60L%60NzWlZzk%40lEhJj%40zAnB%7EFbBbHxChO%7EKtj%40fAdGfApKb%40vIHlHIbGoJlnB%7BPtiDyCrj%40a%40jFcAdIgArHy%40vFSbCB%7CEPvBf%40hC%7C%40hCrCfFfBbDfClFfB%7EEdEnMzOzg%40lIfUjIbTfHfRnEjM%40%5C%3FXCTM%5EgAp%40aC%7CAwFhDeHhEgUdN_DlBeCpBgD%7CD%7BBjDyEpI%7BDdFiArAaL%7CLmFjGoKfNwMbRiCrCyCjCcGvD%7DHfEqWrNyXtPgJvFqB%7E%40%7BBb%40yBBmAMmEaAkA%3FmAPs%40RuBnAoC%60BgDxAeB%5EoBJa%40%40iEm%40cGwAoGcAuBOuBBsBZuAd%40yA%60AuAzAy%40jAIf%40_AdCiB%60FmE%7ELq%40%60DY%60DAbAHfERtHEbBk%40nDuAjDwBjCuBxByAzBq%40bAsAbEqAbFmBfJo%40bCuAzCmA%60BgB%7EA%7DDtBgLrFoDfBoBnAoC%7EByDpF%7DDlGwGjKeJbOoHrNyC%7CDkGnG%7DAjCw%40fBwBnGqAbCq%40x%40wAhAsFzDwBxB%7BA%60CcGhKs%40%7EAgAnDuAjGcAlCaAbBsCfD%7DN%7EPwH%60JaExFiEbGyAzAwCtBkAj%40qDpAmLbEwBdAeHdEcIbFcJ%7CFeCdBkAlAgFfJq%40nAwBpC%7DBfBoQjKaMxHmBlBqAvBk%40%7CAaAtEyBjLiG%7E%60%40kA%7CGcAjEaBbGiWh_AgJx%5Cs%40lCeAjFo%40tE%5DhDOfCUd%40c%40L&key=AIzaSyBUjR5xuzBIA_BGGkxnUeHFvLRslstJOU0
That goes in an img tag like so:
<img src="$url_route_img">
Included in an img tag, I see this:
My key is only valid for our server's IP, which is entered in the API key config screen under Restrictions. I've also specifically allowed the Directions and Static Maps APIs on the same key config (the directions part works fine).
What am I missing to get a static image of a route to appear?

Static Maps API requires HTTP based restriction, while Directions was looking for IP based restriction.
I created a second API key specifically for Static Maps and configured using HTTP restriction.
Image now loads perfectly.

Related

Setting link URL with Google Docs API doesn't result in update of image

I'm trying to update a placeholder image with a new image that has an updated URL. The URL in fact is a valid Google Static Map URL that I'm using in other contexts successfully. I'm using the Google Document API to manipulate the document. Following the code I've been using:
var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
var imageMap = element.asInlineImage();
// if there was an image found in document
if (imageMap != null) {
// get current parent and index inside parent
var parent = imageMap.getParent();
var childIndex = parent.getChildIndex(imageMap);
// remove image from paragraph
imageMap = imageMap.removeFromParent();
// get static image url for territory
var url = getStaticMapURLForTerritory(id);
Logger.log(url);
imageMap.setLinkUrl(url);
// create a new image
parent.insertInlineImage(childIndex, imageMap)
}
This seems to work fine in that it does update the image url correctly. However, the image itself (the result of the url) is not updated. When I click on the link URL it does return the correct image.
Is there a way to force a refetch of the image blob associated with the URL? I've also attempted to use UrlFetchApp but that complains about a missing size parameter (google static api) which is certainly included in the url string and within the max 640x640 bounds.
I've exhausted all my options unless....
TIA, --Paul
setLinkUrl only does that: sets the link. To actually add a new image you'll have to get its blob:
function replaceImage() {
// [...]
// get static image url for territory
const url = getStaticMapURLForTerritory(id)
const response = UrlFetchApp.fetch(url)
// create a new image
parent.insertInlineImage(childIndex, response.getBlob())
.setAltDescription(img.getAltDescription())
.setAltTitle(img.getAltTitle())
.setWidth(img.getWidth())
.setHeight(img.getHeight())
.setLinkUrl(url)
}
References
Class InlineImage (Google Apps Script reference)

Modify RewriteContext Host in NetCore 2 rewriting middleware

I need to rewrite not redirect certain requests to GET files to an external storage location (hosted on a different domain)
I am able to accomplish this with redirecting using rewriter middleware, however i would like to rewrite instead.
I need to use some logic to rewrite to a specific file location, so I followed https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-2.0&tabs=aspnetcore2x#method-based-rule tutorial.
When i set the Host and path i can see the absolute url looks correct but when the method exits i get "No webpage was found for the web address:" and url displayed is the original request Url
RewriteRule.cs (also holds redirect url logic in ApplyRule() that i don't want to use)
public static void RewriteStorageFileRequests(RewriteContext context)
{
var request = context.HttpContext.Request;
var path = request.Path.Value;
if (path.Contains("foo/bar"))
{
context.Result = RuleResult.SkipRemainingRules;
request.Host = new HostString("storage/space");
request.Path = path.Replace("foo/bar", string.Empty);
var test2 = request.GetDisplayUrl();
}
}
So essentially, if a call comes in as:
https://localhost:44327/foo/bar/bf34d911-03db-5tda-9c99-c7dd96593159/w3.jpg
I want to rewrite it to:
https://storage/space/bf34d911-03db-5tda-9c99-c7dd96593159/w3.jpg
Startup.cs
app.UseRewriter(new RewriteOptions().Add(RewriteUrlRule.RewriteStorageFileRequests));
test2 displays the correct url in the debugger.
I tried setting host to empty string and passing host value (storage/space) in path but still no luck.
Before Rewriter
After Rewrite
UPDATE: I was able to get rewrite to work by changing
context.Result = RuleResult.SkipRemainingRules;
to
context.Result = RuleResult.EndResponse;
However, when i get to the Url it returns 200OK but does not show the image.
(see attached file)
So, right now the only way i can get images is still with Redirect
Rewrite GET

google rest api reverse image search

I am trying to do a reverse image search with the Google REST API with an image stored locally. I am using the new--not deprecated--REST API. I can do a text search and get results. I can not do a search with a local image. I can do a reverse image search on the image and get a result. Any suggestions?
My https string is:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
Also, tried this https string, which doesn't work either:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&searchType=image&q=file:///home/givonz/donald-trump-voicemail-feature.jpg
This text string search works:
https://www.googleapis.com/customsearch/v1?key=A******&cx=0****&q=Some+String
It seems the service is deprecated and no longer available as an API and; it always needed a link (URL). There are a few services on the web that seem to provide the function. Bing, in spite of appearing to do so, doesn't seem to. Yahoo does a reverse image search, but, I couldn't find an API. "Incandescent" does provide this service and with an API.
This should work. Make sure you pass your key in the header.
var path = #"YOUR_IMAGE_PATH";
var url = "https://api.cognitive.microsoft.com/bing/v7.0/images/details?modules=similarimages";
using (var client = new HttpClient())
using (Stream imageFileStream = File.OpenRead(path))
{
var content = new MultipartFormDataContent();
var strContent = new StreamContent(imageFileStream);
strContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = "anynameworks" };
content.Add(strContent);
var message = await client.PostAsync(url, content);
return await message.Content.ReadAsStringAsync();
}

Vaadin Image URL from StreamResource

I get my images from my database via the StreamResource and use afterwards the Image() class to show the picture. Is it possible to get from this StreamResource or Image class the URL?
Through the browser I can find out that the image has the URL that looks like: "... / Web/APP/connector/0/32/source/Picture-xxx.JPG"
I need the URL to the image for CSSInject.
Thanks in advance
So..
Client side Vaadin resource link pattern is like:
[protocol]+"://"+[currentUrl]+"/APP/connector/"+[uiId]+"/"+[cid]+"/source/"+[filename]
where:
protocol - request protocol,
currentUrl - current URL,
uiId - Vaadin UI identifier,
cid - connector identifier,
filename - filename.
Example function to get url:
String getResourceURL(AbstractClientConnector connector,FileResource resource){
String protocol = UI.getCurrent().getPage().getLocation().getScheme();
String currentUrl = UI.getCurrent().getPage().getLocation().getAuthority();
String cid = connector.getConnectorId();
Integer uiId = connector.getUI().getUIId();
String filename = resource.getFilename();
return protocol+"://"+currentUrl+"/APP/connector/"+uiId+"/"+cid+"/source/"+filename;
}
where:
connector is for example Image object
resource is FileResource
This is a typical use case for creating a request handler:
As mentioned in the provided link:
Request handlers are useful for catching request parameters or generating dynamic content, such as HTML, images, PDF, or other content.

Windows Azure REST API MediaLink

I'm trying to use the API REST of Windows Azure for creating a virtual machine deployment. However, I've got a problem when trying to specify an OS image in the following XML file:
<Deployment xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>SomeName</Name>
<DeploymentSlot>Production</DeploymentSlot>
<Label></Label>
<RoleList>
<Role i:type="PersistentVMRole">
<RoleName>SomeName</RoleName>
<OsVersion i:nil="true"/>
<RoleType>PersistentVMRole</RoleType>
<ConfigurationSets>
<ConfigurationSet i:type="WindowsProvisioningConfigurationSet">
<ConfigurationSetType>WindowsProvisioningConfiguration</ConfigurationSetType>
<ComputerName>SomeName</ComputerName>
<AdminPassword>XXXXXXXXXX</AdminPassword>
<EnableAutomaticUpdates>true</EnableAutomaticUpdates>
<ResetPasswordOnFirstLogon>false</ResetPasswordOnFirstLogon>
</ConfigurationSet>
<ConfigurationSet i:type="NetworkConfigurationSet">
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>
<InputEndpoint>
<LocalPort>3389</LocalPort>
<Name>RemoteDesktop</Name>
<Protocol>tcp</Protocol>
</InputEndpoint>
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<DataVirtualHardDisks/>
<Label></Label>
<OSVirtualHardDisk>
<MediaLink>¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿???????????????</MediaLink>
<SourceImageName>¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿??????????????????</SourceImageName>
</OSVirtualHardDisk>
</Role>
</RoleList>
</Deployment>`
I need the MediaLink (URI of the OS image) and the SourceImageName (Canonical name of the OS image). My question is, the web portal provides several PREDEFINED images but I cannot determine the URI and the canonical name of them. Will I be forced to create my own OS image and upload it to any of the storage services under my Windows Azure account?
To get these parameters, you could perform List OS Images Service Management API operation on your subscription.
UPDATE
Please discard some of my comments below (sorry about those). I was finally able to create a VM using REST API :). Here're some of the things:
<MediaLink> element should specify the URL of the VHD off of which your VM will be created. It has to be a URL in one of your storage account in the same subscription as your virtual machine cloud service. So for this, you could specify a URL like: https://[yourstorageaccount].blob.core.windows.net/[blobcontainer]/[filename].vhd where [blobcontainer] would be the name of the blob container where you would want the API to store the VHD while the [filename] is any name that you want to give to your VHD. What REST API does is that it copies the source image specified in the <SourceImageName> and saves it at the URI specified in the <MediaLink> element.
Make sure that your Service and Storage Account where your VHD will be stored are in the same data center/affinity group. Furthermore that data center should be able to support Virtual Machines. It turns out that not all data centers support Virtual Machines.
Order of XML element is of utmost importance. You move one element up or down would result in 400 error.
Based on my experimentation, here's the code:
private static void CreateVirtualMachineDeployment(string subscriptionId, X509Certificate2 cert, string cloudServiceName)
{
try
{
string uri = string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments", subscriptionId, cloudServiceName);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.Headers.Add("x-ms-version", "2013-03-01");
request.ClientCertificates.Add(cert);
string requestPayload = #"<Deployment xmlns=""http://schemas.microsoft.com/windowsazure"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<Name>[SomeName]</Name>
<DeploymentSlot>Production</DeploymentSlot>
<Label>[SomeLabel]</Label>
<RoleList>
<Role i:type=""PersistentVMRole"">
<RoleName>MyTestRole</RoleName>
<OsVersion i:nil=""true""/>
<RoleType>PersistentVMRole</RoleType>
<ConfigurationSets>
<ConfigurationSet i:type=""WindowsProvisioningConfigurationSet"">
<ConfigurationSetType>WindowsProvisioningConfiguration</ConfigurationSetType>
<ComputerName>[ComputerName]</ComputerName>
<AdminPassword>[AdminPassword - Ensure it's strong Password]</AdminPassword>
<AdminUsername>[Admin Username]</AdminUsername>
<EnableAutomaticUpdates>true</EnableAutomaticUpdates>
<ResetPasswordOnFirstLogon>false</ResetPasswordOnFirstLogon>
</ConfigurationSet>
<ConfigurationSet i:type=""NetworkConfigurationSet"">
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>
<InputEndpoint>
<LocalPort>3389</LocalPort>
<Name>RemoteDesktop</Name>
<Protocol>tcp</Protocol>
</InputEndpoint>
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<DataVirtualHardDisks/>
<Label></Label>
<OSVirtualHardDisk>
<MediaLink>https://[storageaccount].blob.core.windows.net/vhds/fb83b3509582419d99629ce476bcb5c8__Microsoft-SQL-Server-2012SP1-Web-CY13SU04-SQL11-SP1-CU3-11.0.3350.0.vhd</MediaLink>
<SourceImageName>fb83b3509582419d99629ce476bcb5c8__Microsoft-SQL-Server-2012SP1-Web-CY13SU04-SQL11-SP1-CU3-11.0.3350.0</SourceImageName>
</OSVirtualHardDisk>
</Role>
</RoleList>
</Deployment>";
byte[] content = Encoding.UTF8.GetBytes(requestPayload);
request.ContentLength = content.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(content, 0, content.Length);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
catch (WebException webEx)
{
using (var streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
}
Hope this helps!

Resources