Bing Map pushpins not displaying on an Office365 SharePoint page - javascript

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.

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?

How to do labeled markers in here maps with JavaScript API?

I'm trying to create labeled markers in the here maps, some like google maps, but I didn't find how.
Something like code bellow.
marker.setLabel('label')
I didn't find in the documentation a easy way to do this. I solved this problem using the DomMarker. The solution is below.
function createMarker(point, ico, label = ''){
var html = document.createElement('div'),
divIcon = document.createElement('div'),
divText = document.createElement('div'),
imgIco = document.createElement('img');
imgIco.setAttribute('src', ico);
divIcon.appendChild(imgIco);
divText.innerHTML = label;
html.appendChild(divIcon);
html.appendChild(divText);
var domIcon = new H.map.DomIcon(html);
var marker = new H.map.DomMarker(point, {
icon: domIcon
});
return marker;
}

Display Shapefile with leaflet and layer control

Hello
I try to implement a leaflet pluging, for display a local hosted shapefile. The display of the shapefile work, but i want to add a layer control (for togle shapefile layer).
the plugin link : https://github.com/calvinmetcalf/shapefile-js
the demo link :http://leaflet.calvinmetcalf.com/#3/32.69/10.55
I want to implement the layer control on demo page
<script>
var m = L.map('map').setView([0, 0 ], 10);
var watercolor =
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen
Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY
3.0</a> — Map data © OpenStreetMap contributors, CC-BY-SA'
}).addTo(m);
var shpfile = new L.Shapefile('Fr_adm.zip', {
onEachFeature: function(feature, layer) {
if (feature.properties) {
layer.bindPopup(Object.keys(feature.properties).map(function(k) {
return k + ": " + feature.properties[k];
}).join("<br />"), {
maxHeight: 200
});
}
}
});
shpfile.addTo(m);
shpfile.once("data:loaded", function() {
console.log("finished loaded shapefile");
});
// initialize stylable leaflet control widget
var control = L.control.UniForm(null, overlayMaps, {
collapsed: false,
position: 'topright'
}
);
// add control widget to map and html dom.
control.addTo(m);
</script>
The shapefile Fr_adm.zip is displayed, but no layer control.
Thank for your help.
Your problem is that overlayMaps is not defined. Open your console and you should see an error stating this.
Looking at the documentation for L.control.UniForm maps (an extension of leaflet), we can see:
/ **
* standard leaflet code.
** /
// initialize stylable leaflet control widget
var control = L.control.UniForm(null, overlayMaps, {
collapsed: false,
position: 'topright'
}
);
What is overlayMaps in this? To answer we need to take a look at the documentation for standard leaflet code. overlayMaps is a list of key, object pairs:
... we’ll create two objects. One will contain our base layers and
one will contain our overlays. These are just simple objects with
key/value pairs. The key sets the text for the layer in the control
(e.g. “Streets”), while the corresponding value is a reference to the
layer (e.g. streets).
var baseMaps = {
"Grayscale": grayscale,
"Streets": streets
};
var overlayMaps = {
"Cities": cities
};
Consequently, overlayMaps in your example should look like:
var overlayMaps = {"Name To Display":shpfile }
Once defined you should be able to create your layer control as normal.
i see a mistake in the code, no overlayer value. So i try with this :
<script type="text/javascript" charset="UTF-8">
//----------------
var watercolor = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
});
var geo = L.geoJson({features:[]},{onEachFeature:function popUp(f,l){
var out = [];
if (f.properties){
for(var key in f.properties){
out.push(key+": "+f.properties[key]);
}
l.bindPopup(out.join("<br />"));
}
}});
var m = L.map('map', {
center: [10, -1],
zoom: 6,
layers: [watercolor, geo ]
});
//}}).addTo(m);
var base = 'Fr_admin.zip';
shp(base).then(function(data){
geo.addData(data);
});
var baseMaps = {
"BaseLayer": watercolor
};
var overlays = {
"shapefile": geo
};
L.control.layers(baseMaps,overlays).addTo(m);
</script>
It 's work, i can chose to display the shapefile or not.
But dont return all segmentation like here :http://leaflet.calvinmetcalf.com/#3/32.69/10.55
thank you

Save an Image object from my Webpage to File

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

Google Maps V3 JavaScript works only in Chrome?

I wrote a script that first geocodes an address and then displays a map of that address.
The trouble is, it only works in Chrome / Chromium. Other browsers (Firefox 10 & IE9) display a grey box. A problem that could be related, if I add a marker to the map, the marker does not show in Chrome.
I know that :
I connect with the API successfully with my API key.
The address is properly geocoded.
I use jQuery UI dialog to display the map. This, however, does not seem to be a problem. Removing the dialog and using a static div creates the same "grey box" result.
Below is my script, how I invoke it, and the website that I am using this on.
Here's the script:
function Map(properties)
{
var that = this;
// the HTML div
this.element = properties.element;
// address string to geocode
this.address = properties.address;
// title to use on the map and on the jQuery dialog
this.title = properties.title;
this.latlng = null;
this.map = null;
this.markers = [];
// geocode address and callback
new google.maps.Geocoder().geocode({'address': this.address}, function(data)
{
// geocoded latitude / longitude object
that.latlng = data[0].geometry.location;
// map options
var options =
{
zoom: 16,
center: that.latlng,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create a map
that.map = new google.maps.Map(that.element, options);
// add a marker
that.markers.push(new google.maps.Marker({map: that.map,
position: that.latlng,
title: that.title + "\n" +
that.address}));
});
this.get_google_map = function()
{
return that.map;
}
// creates a jQuery UI dialog with a map
this.show_in_dialog = function()
{
// because the dialog can resize, we need to inform the map about this
$(that.element).dialog({ width: 400, height: 300, title: that.title,
resizeStop: function(event)
{
google.maps.event.trigger(that.map, 'resize');
},
open: function(event)
{
google.maps.event.trigger(that.map, 'resize');
}});
}
this.center = function()
{
that.map.setCenter(that.latlng);
}
}
Here's how I invoke it :
// grab the address via HTML5 attribute
var address = $("#address").attr("data-address");
// ... and the title
var title = $("#address").attr("data-title") + " Map";
var map_element = document.createElement('div');
// append the newly created element to the body
$("body").append(map_element);
// create my own map object
var map = new Map({ element : map_element,
address : address,
title : title });
// bind a link to show the map
$("#map_link").click(function()
{
map.center();
map.show_in_dialog();
return false;
});
And here's the URL of the problem (click on map):
http://testing.fordservicecoupons.com/dealer/30000/premium_coupon_page
Last but not least, I combine and obfuscate my JavaScripts, so what you see above is not exactly the same as in the source on the website.
This doesn't look good:
resizeStop: function(event) { google.maps.event.trigger(that.element, 'resize'); },
open: function(event) { google.maps.event.trigger(that.element, 'resize'); }
you trigger the resize-event on the element that contains the map(that.element), but you must trigger resize on the google.maps.Map-object (what should be that.map in this case)
Wow... Here was the issue.
The layout that I built was a fluid layout. So, one of the first CSS rules that I have written was:
img, div { max-width: 100%; }
So that divs and images can scale. Well, for whatever reason, Google maps DOES NOT like this rule with the end result being a grey box.
And so I added another rule - an exception for Google maps:
img.no_fluid, div.no_fluid { max-width: none; }
And then, in javascript:
// AFTER DIALOG CREATION
$(dialog).find('*').addClass("no_fluid");
The find('*') will get us all the descendants.
Viola!

Categories