Save an Image object from my Webpage to File - javascript

I am using VB with ASP. I have an ASP Image control that contains an image which in this case, is a static map brought in from Google Maps. I would like to use VB code do download that image to an image (bmp, jpg, or anything). The image resides in an asp:Image object on the client side. Just need to download the image using code from the server side. If necessary, I could use JS on the client side to do this. In that case, I would still like to see if anyone out there knows how to do this.
Here is my javascript code to load the map displayed on the page to an asp:image object. This part works great. Just need to save the image as a file. There are predefined variables in prior code on the page that this function is using including "Map", "Map Options", "Bounds" and "Markers"
function Export() {
map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//URL of Google Static Maps.
var staticMapUrl = "https://maps.googleapis.com/maps/api/staticmap";
//Set the Google Map Center.
staticMapUrl += "?center=" + mapOptions.center.G + "," + mapOptions.center.K;
//Set the Google Map Size.
staticMapUrl += "&size=220x350";
//Set the Google Map Zoom.
staticMapUrl += "&zoom=" + mapOptions.zoom;
//Set the Google Map Type.
staticMapUrl += "&maptype=" + mapOptions.mapTypeId;
//Loop and add Markers.
for (var i = 0; i < markers.length; i++) {
var data = markers[i];
if (data.pointNumber !== null) {
var labelNumber = data.pointNumber;
var labelString = labelNumber.toString();
var iconName = 'm' + labelString + '.png';
var roundLat = data.latitude; // + .00003;
var roundLon = data.longitude; // + .000005;
var myLatlng = new google.maps.LatLng(roundLat, roundLon);
var image =
{
url: 'ImagesForPoints/' + iconName,
scaledSize: new google.maps.Size(35, 48), // scaled size
//size: new google.maps.Size(53, 73),
//origin: new google.maps.Point(0,0),
//anchor: new google.maps.Point(30, 69)
anchor: new google.maps.Point(19, 45)
};
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
bounds.extend(marker.position);
map.fitBounds(bounds);
}
}
//Display the Image of Google Map.
var imgMap = document.getElementById("imgMap");
imgMap.src = staticMapUrl;
imgMap.style.display = "block";
}

Since your using Google Maps Static API, which generates an image from a URL, your server side VB ASP.NET code only needs the URL that was used to generate the image, for it to be able to download it.
For example, the following URL from the Google Maps Static API will provide an image centered on Brooklyn Bridge, New York:
https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Clabel:C%7C40.718217,-73.998284
Your server side code will therefore need this URL to be able to download the exact same image. You could possibly get this URL to your server application in the possible following ways:
Send the URL back as HTML form submission (postback).
Write a web service that accepts a URL for download.
Since you appear to be using ASP.NET web forms, the first option would be your easiest choice for now. All you will need to do is to add a asp:HiddenField control to your page
<asp:HiddenField ID="MapURL" runat="server" ClientIDMode="static" />
and then set the value of the field in you JavaScript export function:
var mapUrlField = document.getElementById('<%= MapURL.ClientID %>');
if (mapUrlField)
{
mapUrlField.value = staticMapUrl;
}
And then on the on postback server-side, you can retrieve the URL from the hidden field and then use the WebClient to download the image.
Dim SaveFilePath as String = "c:\folder\mymap.png"
Dim Client as new WebClient
Client.DownloadFile(MapURL.Value, SaveFilePath )
Client.Dispose

Related

Updating Google Maps Long/Lat

I am trying to update a store location by getting the lat/long of a marker on the google map.
However I get this error:
UpdateStoreDAO.js:7 Uncaught TypeError: Cannot read property 'getPosition' of undefined
at updateItemData (UpdateStoreDAO.js:7)
at UpdateStore.js:68
at IDBOpenDBRequest.request.onsuccess (indexedDB.js:38)
I'm not quite sure why it won't work as getPosition works for adding a store location to the map for a marker. It uses the same Google Maps API as my adding page does and the add page never threw me this error.
The code for the update function (DAO) is:
function updateItemData(marker) {
//User input of item name
var storeLocation = $('#txtStoreLocation').val();
//Get latitude and longitude of current marker position
var eventLat = marker.getPosition().lat();
var eventLng = marker.getPosition().lng();
//Create an item object combining name, desc and price attributes
data.storeLocation = storeLocation;
data.eventLat = eventLat;
data.eventLng = eventLng;
var data = {
'storeLocation' : storeLocation,
'eventLat' : eventLat,
'eventLng' : eventLng
}
//Insert data into indexedDB database
updateOne(data, function(lastID) {
event.preventDefault();
return false;
});
}
The code for the update store js file is (if it's any help):
//mapCenter
var mapCenter = new google.maps.LatLng(51.8979988098144,-2.0838599205017);
//geocoder will be used to convert geographic coordinates (current marker position)
// intop a human-readable address
var geocoder = new google.maps.Geocoder();
//An InfoWindow displays content (usually text or images)
//in a popup window above the map, at a given location.
var infowindow = new google.maps.InfoWindow();
function initialize(){
// Initial map properties
var mapOptions = {
zoom: 15,
center: mapCenter
};
//Create a map object passing the html div placeholder to hold google map
myMap = new google.maps.Map(document.getElementById("mapInput"), mapOptions);
//Create a draggable marker icon in the map
marker = new google.maps.Marker({
map: myMap,
position: mapCenter,
draggable: true
});
}
//Retrieve Item information saved in database
//show in the form
var urlParams = new URLSearchParams(window.location.search);
var itemID = urlParams.get('itemID');
$('#itemID').html("Item ID: " + itemID);
setDatabaseName('dbCatalogue', ['UsersObjectStore', 'ItemsObjectStore']);
setCurrObjectStoreName('ItemsObjectStore');
//Select One function to retrieve data of a specific item
var data;
startDB(function () {
selectOne(itemID, function(result) {
$('#txtStoreLocation').val(result.storeLocation);
$('#txtEventLat').val(result.eventLat);
$('#txtEventLng').val(result.eventLng);
data = result;
})
})
//The addDomListener will be triggered when the HTML page is loaded
//and will execture the initialize function above
google.maps.event.addDomListener(window, 'load', initialize);
//Event handler for form submit button
$('#formUpdateStore').submit(function(event){
// cancels the deafult form submission and handle the event from javascript
event.preventDefault();
//Create an idexedDB database (the name of the database is dbFlogger)
// with two object stores - UsersObjectStore to store user data
// and ItemsObjectStore to store item data
setDatabaseName('dbEvent', ['EventObjStore']);
// For this example, we will store data in ItemsObjectStore
setCurrObjectStoreName('EventObjStore');
//startDB will create a connection with the database and
//execute operations such as save item
startDB(function () {
updateItemData(data);
alert("Store has been updated successfully!");
});
});
I understand it's probably a lot to ask but any help would be appreciated!
(note = comments are a bit off since code has been reused from other pages)
===UPDATE===
I fixed the error by changing updateItemData(data) to updateItemData(marker) in the regular js file.
However, I am now getting a new error:
Uncaught TypeError: Cannot set property 'storeLocation' of undefined
at updateItemData (UpdateStoreDAO.js:11)
at UpdateStore.js:68
at IDBOpenDBRequest.request.onsuccess (indexedDB.js:38)
I'm not quite sure why I'm getting this as storeLocation is defined and there's a property set via user input?

Trying to Replicate Code but Map Won't Populate in Background

I'm trying to recreate the Leaflet map from the following link.
http://bl.ocks.org/adg29/6f5f9750afaae0ce68a8
However, like in the url, I can't get a map to populate in the background - which it does here (the link below) and to my recollection the code is the same. Can someone assist me with this?
Where map works:
http://zevross.com/blog/2014/09/30/use-the-amazing-d3-library-to-animate-a-path-on-a-leaflet-map/
Here is my code (w/ public access token):
L.mapbox.accessToken = '<access token>';
var mapboxTiles =
L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-
zr0njcqy/{z}/{x}/{y}.png', {
attribution: '<a href="http://www.mapbox.com/about/maps/"
target="_blank">Terms & Feedback</a>'
});
var map = L.map('map', {accessToken: '<access token>'})
.addLayer(mapboxTiles)
.setView([40.72332345541449, -73.99], 14);

OpenLayers Map markers disappear when map is centered on them

I'm having issues with the OpenLayers map markers. I have searched through the other answers here and on other sites but non of them really addressed the issue I'm having (at least I don't think they did. I'm fairly new to OpenLayers and Javascript, my apologies if I am wrong).
The markers appear when I load the map and page, and no errors display in the console. When I pan to the markers, as they cross into the middle third of the map at max extent, they disappear! When I zoom in, they disappear before I can even get them on screen (never errors from the console). Here is my javascript code for generating the map and markers. Thank you in advance for all of your help.
Additional notes: When I use static numbers (and not values retrieved from my XML file) for marker positioning, the markers do not disappear on pan or zoom. I am so confused.
RESOLVED: I used a different XML file and the markers stopped disappearing for some reason, I have no idea why.
Code:
$(function()
{
var map = new OpenLayers.Map("rcp1_map");
layer = new OpenLayers.Layer.OSM("OpenStreetMap");
map.addLayer(layer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(0, 0), 3);
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
//load and retrieve values from XML file here
var xmlDoc=loadXMLDoc("http://whxlab3.dart.ns.ec.gc.ca/~brinka/
EMETsiteV1/EMETsite.xml");
var z=xmlDoc.getElementsByTagName("buoy_number");
var y=xmlDoc.getElementsByTagName("lat");
var x=xmlDoc.getElementsByTagName("long");
//create and add all map markers here
for(i=0; i<x.length; i++)
{
//use loaded XML file to retrieve values for marker positions
var px = x[i].childNodes[0].nodeValue;
var py = y[i].childNodes[0].nodeValue;
var pz = z[i].childNodes[0].nodeValue;
console.log("Testing Console", px, py);
var size = new OpenLayers.Size(32, 37);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('stock_images/buoy_arrow.png', size,
offset);
icon.setOpacity(0.7);
var lonlat = new OpenLayers.LonLat(px, py);
lonlat.transform(new OpenLayers.Projection("EPSG:4326"),
new OpenLayers.Projection("EPSG:900913"));
var marker = new OpenLayers.Marker(lonlat, icon);
marker.events.register("mouseover", marker, function(){
console.log("Over the marker "+this.id+" at place
"+this.lonlat);
this.inflate(1.2);
this.setOpacity(1);
});
marker.events.register("mouseout", marker, function(){
console.log("Out the marker "+this.id+" at place
"+this.lonlat);
this.inflate(1/1.2);
this.setOpacity(0.7);
});
marker.events.register("click", marker, function(){
console.log("Clicked "+this.id+" at place "+this.lonlat);
popup = new OpenLayers.Popup.FramedCloud("chicken",
marker.lonlat, new OpenLayers.Size(200, 200),
("Buoy Number: "+pz), null, true);
map.addPopup(popup);
});
markers.addMarker(marker);
}
//:*** To here
});

Bing Map pushpins not displaying on an Office365 SharePoint page

I have an Office 365 SharePoint site where I am trying to display data from a list that contains geolocation data using the Bing Maps ajax control (http://msdn.microsoft.com/en-us/library/gg427610.aspx). My map is loading up correctly and displaying the correct location but the actual pushpins are not displaying. I've tried default and custom pushpin icons to no avail. When I use similar JavaScript on a 'vanilla' html page, the pushpins display just fine so I think there must be some sort of conflict with the SharePoint JavaScript or css.
Here the relevant block of code:
function fillListData(web, list, items) {
var tile = $("#" + tileId);
var content = tile.find('.tileContent');
var mapOptions = {
credentials: "",
mapTypeId: Microsoft.Maps.MapTypeId.auto,
showDashboard: false
};
var map = new Microsoft.Maps.Map(content[0], mapOptions);
var locs = [];
var e = items.getEnumerator();
while (e.moveNext()) {
var listItem = e.get_current();
var title = listItem.get_item("Title");
var loc = listItem.get_item("Location");
var lat = loc.get_latitude();
var lon = loc.get_longitude();
var mapLoc = new Microsoft.Maps.Location(lat, lon);
locs.push(mapLoc);
//var pin = new Microsoft.Maps.Pushpin(mapLoc, {text: title, visible: true, icon:'../Style Library/Images/flag_red.png'});
//var pin = new Microsoft.Maps.Pushpin(mapLoc, {visible: true, icon:'../Style Library/Images/flag_red.png', width: 50, height: 50});
var pin = new Microsoft.Maps.Pushpin(mapLoc);
map.entities.push(pin);
}
var bestView = Microsoft.Maps.LocationRect.fromLocations(locs);
map.setView({bounds:bestView });
}
Any insights are appreciated.
Thanks.
Double check the lat and lon values. Make sure they actually have a value and that it is a number and not a string. If it is a string use parseFloat to convert it to a number. Numbers that are stored as a string is a fairly common cause for pushpins not displaying as the Location class ends up being invalid.
Incase anyone else comes across this problem, going into your internet settings, lowering protection levels and going into "Custom Levels", finding "Enable mixed content" and enabling that has been the solution for two machines here.

Take screenshot of google map [duplicate]

I'm working on functionality to take snapshot of google map with polylines and open popup window on polyline click on google map.
The snapshot of google map with polylines is working
but it will not able to take snapshot open popup window on polyline.
polyline are showing on sanpshot picture but info window are not showing .
Here is code to take snapshot.
This code is to initialize the code control on javascript onload :
var snapShotControlOptions = { hidden: true };
snapShotControlOptions.buttonLabelHtml="<snap id='snap' style='display:none' >snap</span>"
snapShotControl = new SnapShotControl(snapShotControlOptions);
map.addControl(snapShotControl);
here is the method take snap to take the sanp shot of google map .
function takeSnap() {
//static map size
var sizeStr = "640x640";
var imgSize = "";
if (sizeStr != "") {
var sizeArray = sizeStr.split("x");
imgSize = new GSize(sizeArray[0], sizeArray[1]);
}
snapShotControl.setMapSize(imgSize);
var format = "jpg";
snapShotControl.setFormat(format);
var url = snapShotControl.getImage();
// document.getElementById("snapshot_canvas").src = url;
SaveImage(url);
//
}
//this will add polyline overlay to draw line on google map with different color of polyline on google map .
var polyline = directionsArray[num].getPolyline();
polyline.setStrokeStyle({ color: streetColor, weight: 3, opacity: 0.7 });
polyline.ssColor=streetColor;
map.addOverlay(polyline);
///this code will open the pop info window on polyline those polyline created on google map
and problem is their these pop window not included on sanpshot when i take sanpshot of google map.
var MousePoint = "";
var marker;
GEvent.addListener(map, "mousemove", function (point) {
MousePoint = new GLatLng(point.lat(), point.lng());
});
GEvent.addListener(polyline, "click", function () {
map.openInfoWindowHtml(MousePoint, headMarkerHtml);
});
GEvent.addListener(polyline, "mouseout", function () {
// map.closeInfoWindow();
});
can you please tell who i pass popup window in polyline overlay .
i have use javascript file snapshotcontrol.js to take the snapshot.
from the snapshotcontrol source
This library makes it easy to generate an image "snapshot" of your
interactive map, using the Google Static Maps API.
Static maps doesn't support info windows or anything like adding custom text to the map
https://developers.google.com/maps/documentation/staticmaps/index
You could draw the map on a canvas within the browser then
draw the info window on top of that using this http://html2canvas.hertzen.com/
and then download the canvas content

Categories