Google is undefined in infobox.js - google-maps

I have a Google map html page. It works fine in development under localhost but when I try to put in online, I get Google undefined in the infobox.js file, with this line:
this.extend(InfoBubble, google.maps.OverlayView);
I have the api key loaded and it's called before I load the infobox.js file. I added the callback=initialize to see if it would work, but it doesn't work with it or without it. Here is the code for the html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Activities</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVVx45quD8ozW5SJZw-Lk_8QvVsXdWi2Y&sensor=false""></script>
<script type="text/javascript" src="GoogleMaps/Scripts/downloadxml.js"></script>
<script type="text/javascript" src="GoogleMaps/Scripts/infobubble_tabs.js"></script>
<style type="text/css">
html, body { height: 100%; }
.style1
{
width: 758px;
}
.style2
{
width: 349px;
}
#side_bar
{
height: 550px;
width: 349px;
overflow:scroll;
}
</style>
<script type="text/javascript">
//<![CDATA[
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
var gmarkers = [];
var gicons = [];
var map = null;
var InfoBubble = new InfoBubble({
maxWidth: 300
});
//defines icon if there is none stated
gicons["red"] = new google.maps.MarkerImage("http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_red.png",
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(9, 9));
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_red.png',
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(9, 9));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
new google.maps.Size(37, 34),
new google.maps.Point(0, 0),
new google.maps.Point(9, 9));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which traces out a polygon as a series of X,Y points. The final coordinate closes
//the poly by connecting to the first coordinate.
var iconShape = {
coord: [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0],
type: 'poly'
};
//determines icon based on category
//if no icon is defined
function getMarkerImage(iconColor) {
if ((typeof (iconColor) == "undefined") || (iconColor == null)) {
iconColor = "red";
}
if (!gicons[iconColor]) {
gicons[iconColor] = new google.maps.MarkerImage(iconColor,
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(9, 9));
}
return gicons[iconColor];
}
function category2icon(category) {
var color = "red";
switch (category) {
case "Hike": color = "GoogleMaps/Images/HikingIcon.jpg";
break;
case "KML": color = "GoogleMaps/Images/kml.gif";
break;
case "Camping": color = "GoogleMaps/Images/camping.gif";
break;
case "StatePark": color = "GoogleMaps/Images/statepark.jpg";
break;
case "NationalPark": color = "GoogleMaps/Images/NationalPark_icon.png";
break;
case "PointsofInterest": color = "GoogleMaps/Images/POI.png";
break;
case "CountyPark": color = "GoogleMaps/Images/CountyPark_Icon.png";
break;
case "Biking": color = "GoogleMaps/Images/Bike_icon.jpg";
break;
case "FishWildlifeService": color = "GoogleMaps/Images/FishWildlife_icon.gif";
break;
case "Kayak": color = "GoogleMaps/Images/kayaking.png";
break;
case "Shelter": color = "GoogleMaps/Images/Shelter_Icon.png";
break;
case "Parking": color = "GoogleMaps/Images/Parking_Lot_Icon.png";
break;
default: color = "red";
break;
}
return color;
}
gicons["Hike"] = getMarkerImage(category2icon("Hike"));
gicons["KML"] = getMarkerImage(category2icon("KML"));
gicons["Camping"] = getMarkerImage(category2icon("Camping"));
gicons["StatePark"] = getMarkerImage(category2icon("StatePark"));
gicons["NationalPark"] = getMarkerImage(category2icon("NationalPark"));
gicons["PointsofInterest"] = getMarkerImage(category2icon("PointsofInterest"));
gicons["CountyPark"] = getMarkerImage(category2icon("CountyPark"));
gicons["Biking"] = getMarkerImage(category2icon("Biking"));
gicons["FishWildlifeService"] = getMarkerImage(category2icon("FishWildlifeService"));
gicons["Kayak"] = getMarkerImage(category2icon("Kayak"));
gicons["Shelter"] = getMarkerImage(category2icon("Shelter"));
gicons["Parking"] = getMarkerImage(category2icon("Parking"));
// A function to create the marker and set up the event window
function createMarker(latlng, name, url, detail_tab, notes_tab, map_tab, hiking_detail_tab, camping_detail_tab, category, state) {
var contentString_detail = detail_tab;
var contentString_notes = notes_tab;
var contentString_maps = map_tab;
var contentString_hiking_detail = hiking_detail_tab;
var contentString_camping_detail = camping_detail_tab;
var marker = new google.maps.Marker({
position: latlng,
icon: gicons[category],
shadow: iconShadow,
map: map,
title: name,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.mystate = state;
marker.myname = name;
gmarkers.push(marker);
// to open the info bubbles
google.maps.event.addListener(marker, 'click', function () {
InfoBubble.open(map, marker);
InfoBubble.removeTab(4);
InfoBubble.removeTab(3);
InfoBubble.removeTab(2);
InfoBubble.removeTab(1);
InfoBubble.removeTab(0);
if (category == "KML") {
window.open("" + url);
}
if (!category == "KML") {
InfoBubble.addTab('Details', contentString_detail);
}
if (!notes_tab == "") {
InfoBubble.addTab('Notes', contentString_notes);
}
if (!map_tab == "") {
switch (category) {
case "Camping": InfoBubble.addTab('Campsite Map', contentString_maps);
break;
case "Hike": InfoBubble.addTab('Trail Map', contentString_maps);
break;
}
}
if (!hiking_detail_tab == "") {
InfoBubble.addTab('Trail Notes', contentString_hiking_detail);
}
if (!camping_detail_tab == "") {
InfoBubble.addTab('Campsite Notes', contentString_camping_detail);
}
});
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category + "box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category + "box").checked = false;
// == close the info window, in case its open on a marker that we just hid
InfoBubble.close();
}
// == a checkbox has been clicked ==
function boxclick(box, category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
makeSidebar();
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = html;
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(39.364032, -77.182159),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Closes any open bubbles before opening new one
google.maps.event.addListener(map, 'click', function () {
InfoBubble.close();
});
//Downloads the data from xml file
// Reads the data the creates each tab
downloadUrl("GoogleMaps/categories.xml", function (doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat, lng);
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var zip = markers[i].getAttribute("zip");
var name = markers[i].getAttribute("name");
var notes = markers[i].getAttribute("notes");
var url = markers[i].getAttribute("url");
var hike_distance = markers[i].getAttribute("hike_distance");
var hike_trail_skill_level = markers[i].getAttribute("hike_trail_skill_level");
var hike_points_of_interest = markers[i].getAttribute("hike_points_of_interest");
var Camping_Amenities = markers[i].getAttribute("Camping_Amenities");
var Camping_Best_Sites = markers[i].getAttribute("Camping_Best_Sites");
var Camping_Notes = markers[i].getAttribute("Camping_Notes");
var image = markers[i].getAttribute("image");
var category = markers[i].getAttribute("category");
//Creates data for Detail Tab
var detail_tab = "";
detail_tab += "<b>" + name + "<\/b><p>";
detail_tab += address + "</br>";
detail_tab += city + ", " + state + " " + zip + "</br>";
detail_tab += '<br><a target="_blank" href="' + url + '">' + url + '</a>' + "</br>";
//Creates data for Notes Tab
var notes_tab = notes;
//Creates data for Maps Tab
var map_tab = "";
if (image) {
map_tab += '<br><a target="_blank" href="' + image + '">' + image + '</a>' + "</br>";
}
//Creates data for Hiking Detail Tab
var hiking_detail_tab = "";
if (hike_distance) {
hiking_detail_tab += "<b>Trail Distance: </b>" + hike_distance + " miles</br>";
hiking_detail_tab += "<b>Trail Skill Level: </b>" + hike_trail_skill_level + "</br>";
hiking_detail_tab += "<b>Points of Interest: </b>" + hike_points_of_interest + "</br>";
}
//Creates data for Camping Detail Tab
var camping_detail_tab = "";
if (Camping_Notes) {
camping_detail_tab += "<b>Amenities: </b>" + Camping_Amenities + "</br>";
camping_detail_tab += "<b>Best Sites: </b>" + Camping_Best_Sites + "</br>";
camping_detail_tab += "<b>Notes: </b>" + Camping_Notes + "</br>";
}
// var kml_tab = "";
// if (category=="KML) {
// create the marker
var marker = createMarker(point, name, url, detail_tab, notes_tab, map_tab, hiking_detail_tab, camping_detail_tab, category);
}
// == show or hide the categories initially ==
show("Hike");
show("KML");
hide("Camping");
hide("StatePark");
hide("NationalPark");
hide("PointsofInterest");
hide("CountyPark");
hide("Biking");
hide("FishWildlifeService");
hide("Kayak");
hide("Shelter");
hide("Parking");
// == create the initial sidebar ==
makeSidebar();
});
}
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<table border="1" >
<tr>
<td class="style1">
<div id="map" style="width:978px; height: 596px"></div>
</td>
<td valign="top" style="text-decoration: underline; color: #4444ff;"
class="style2">
<h4>To view a topo map, click map in the top left corner and select terrain from drop down menu</h4>
<div id="side_bar"></div>
</td>
</tr>
</table>
<form action="#">
Hiking: <input type="checkbox" id="Hikebox" onclick="boxclick(this,'Hike')" />
Full Trail Map: <input type="checkbox" id="KMLbox" onclick="boxclick(this,'KML')" />
Trail Shelters: <input type="checkbox" id="Shelterbox" onclick="boxclick(this,'Shelter')" />
Trail Parking: <input type="checkbox" id="Parkingbox" onclick="boxclick(this,'Parking')" />
Camping: <input type="checkbox" id="Campingbox" onclick="boxclick(this,'Camping')" />
Biking: <input type="checkbox" id="Bikingbox" onclick="boxclick(this,'Biking')" />
Kayaking: <input type="checkbox" id="Kayakbox" onclick="boxclick(this,'Kayak')" />
<br />
State Parks: <input type="checkbox" id="StateParkbox" onclick="boxclick(this,'StatePark')" />
National Parks: <input type="checkbox" id="NationalParkbox" onclick="boxclick(this,'NationalPark')" />
County Park: <input type="checkbox" id="CountyParkbox" onclick="boxclick(this,'CountyPark')" />
<br />
Points of Interest: <input type="checkbox" id="PointsofInterestbox" onclick="boxclick(this,'PointsofInterest')" />
Fish and Wildlife Service: <input type="checkbox" id="FishWildlifeServicebox" onclick="boxclick(this,'FishWildlifeService')" />
<br />
</form>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
</body>
</html>

Remove the callback-parameter. When you use the callback-parameter the asynchronous version of the maps-API will be loaded.
You can't use the asynchronous version of the API here because infobox.js only works when the maps-API has already been loaded(what may happen with the asynchronous version, but must not).
In this special case the API never will be loaded, because the body-element is still unknown (but it must be available, because the script tries to inject another script-element into the body).
When you say that it also doesn't work without the callback-parameter there must be another issue that will not be exposed by the code, please post more code or a demo/link.

Related

Google maps not working IE11 (sharepoint 2010)

I have a code to show Google Maps in my list on Sharepoint 2010. Code plot list items in the map. Work great with Edge and Chrome, but on IE not.
In IE console error on this line (object doesn't support this action (error 445))
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
Full code on Sharepoint:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" type="text/javascript"></script><script src="http://maps.google.com/maps/api/js?key=MY KEY" type="text/javascript"></script><script type="text/javascript">
/* *****************************************************
AND NOW SOME VARIABLES YOU MAY WANT TO CHANGE.
***************************************************** */
var mapWidth = "1725px"; //the width of the map
var mapHeight = "400px"; //the height of the map
//if true the coordinates (latitude, longitude) will be used
//if false the addresses (street, zip, city, country) will be used
var useCoordinates = true;
//if true the map will not be shown by default
//if false the map will be shown by default
var hideMapUntilClick = false;
//if 0 absolutely no warning- and error-alerts will be written to a log-div
//if 1 the warning- and error-alerts will be written to a log-div
//if 2 the warning- and error-alerts will be alerted via javascript-alert
var showWarningAndErrorAlerts = 1;
//the internal-names of list-columns (not the display-name!)
var colLinkTitleInternalName = "ows_Nome_x0020_Instala_x00e7__x00e3_"; //will be used as the title of the geo-markers
var colLongitudeInternalName = "ows_Longitude"; //useCoordinates == true
var colLatitudeInternalName = "ows_Latitude"; //useCoordinates == true
var colStreetInternalName = "WorkAddress"; //useCoordinates == false
var colStreetDisplayName = "Endereço"; //useCoordinates == false
var colZipInternalName = "WorkZip"; //useCoordinates == false
var colCityInternalName = "WorkCity"; //useCoordinates == false
var colCountryInternalName = "WorkCountry"; //useCoordinates == false
var defaultCountryValue = "Brazil"; //the default country which will be used if no country-name will be found in the list-column
//default position (Germany: 51.165691,10.451526) > used if no markers will be set to the map
var defaultLatitude = -15.77972;
var defaultLongitude = -47.92972;
//some language-specific messages
var resxGoogleMapsLink = "Google-Map"; //the name of new menu-point in the menu-toolbar of the sharepoint-list
var resxGoogleMapsLinkTitle = "Menu: Show or hide Google-Map"; //the title which will be visible while hovering
var resxAlertsMessageText = resxGoogleMapsLink+": There are # hints!"; //the hint which will be visible if configuration warnings or errors occured.
var resxAlertsMessageTextTitle = "Click here to show or hide the hints!"; //the title which will be visible while hovering
/* *******************************************************************
NOW DO NOT CHANGE ANYTHING IF YOU ARE NOT FAMILIAR WITH JAVASCRIPT!
******************************************************************* */
var isSharePoint2010 = true;
var hasMapBeenLoadedInitially = false;
var idOfMapDiv = "divGoogleMapForSharePointList";
var idOfCustomLogDiv = "divCustomLog";
var idOfCustomLogOverview = "divCustomLogOverview";
var noOfCustomLogEntries = 0;
var noOfMaxGeocodingRequest = 10;
//the attribute-name of the column "id" > will be used for a) finding the id of a certain row and b) for building the ajax-request-url
var colID = "ID";
//now some templates for jquery-selects
var jQuerySelect_2007_GetListRowByAttributeCTXName = "table[CTXName]";
var jQuerySelect_2010_GetListRowByAttributeCTXName = "div[CTXName]";
function InitializeGoogleMapForSharePointList()
{
BuildGoogleMapCustomLogForSharePointList();
if(!DoPreCheckForInitializationOfGooglemapsForSharePointList())
{
//pre-check not successfully done > abort now!
customAlert("The Pre-Check has not been successfully! > Abort now.");
return;
}
DoSchemaCheckAndBuildGoogleMapIconForSharePointList();
}
function DoSchemaCheckAndBuildGoogleMapIconForSharePointList()
{
//get the schema-data for the list
$.get(BuildAjaxRequestUrlForSharePointListSchemaOnly(), {}, function (xml)
{
//find all necessary internal-field-names
var arrNeccessaryFields = new Array();
arrNeccessaryFields.push(colLinkTitleInternalName);
if(useCoordinates)
{
arrNeccessaryFields.push(colLatitudeInternalName);
arrNeccessaryFields.push(colLongitudeInternalName);
}
else
{
arrNeccessaryFields.push(colStreetInternalName);
arrNeccessaryFields.push(colZipInternalName);
arrNeccessaryFields.push(colCityInternalName);
arrNeccessaryFields.push(colCountryInternalName);
}
//check all neccessary internal-field-names
var foundAllNeccessaryFields = true;
for(i=0;i<arrNeccessaryFields.length;i++)
{
//getting <xml><s:Schema><s:ElementType><s:AttributeType name="[internal-field-name]">
var xmlQuery = 'xml > *:first > *:first > *[name='+arrNeccessaryFields[i]+']';
if($(xmlQuery, xml).length<1)
{
foundAllNeccessaryFields = false;
customAlert("Schema-Check failed for internal-field-name '"+arrNeccessaryFields[i]+"'. The field is not available in this list.");
}
}
//check if the neccessary fields have been found
if(foundAllNeccessaryFields)
{
BuildGoogleMapIconForSharePointList();
}
else
{
var ajaxRequestLinkTag = 'ajax-request for list-schema';
customAlert("Hint: You can get the internal names of the columns by calling the "+ajaxRequestLinkTag+" for the current sharepoint-list manually.");
customAlert("Schema-Check failed. Abort now!");
}
});
}
function DoPreCheckForInitializationOfGooglemapsForSharePointList()
{
//check if this is SharePoint2010 or not
//if it is not 2010 it is assumed that it is 2007
if(typeof(_fV4UI)!='undefined')
{
//the checked javascript-variable exists only in 2010
isSharePoint2010 = true;
}
else
{
isSharePoint2010 = false;
}
//for the first shot: support only one table
//for further version we could support more tables (table[class=ms-listviewtable].length>1)
var noOfListViews = $("table[class=ms-listviewtable]").length;
if(noOfListViews==0)
{
//no list-view exists > there is no need to show google-maps
customAlert("There is no list-view available on this site. > No need to show google-maps. > Abort now.");
return false;
}
else if(noOfListViews>1)
{
//there are more than one list-view > this is not supported at the moment
customAlert("There are more than one list-views on the site. This is not supported at the moment. > Abort now!");
return false;
}
//check if multi-lookup exists
if($("table[FieldType=LookupMulti]").length>0)
{
//If there are columns in the list-view which are of type multi-lookup the ajax-call (via owssrv.dll) will return zero results.
var multiMsg = "Multi-lookup exists! Please remove the mulit-lookup-column or use another view (otherwise the ajax-request will receive an empty result). > Abort now!";
multiMsg += "\n\nColumns which are of type multi-lookup are (the display-name will be shown):";
$("table[FieldType=LookupMulti]").each(function(){
var displayName = $(this).attr("displayName");
multiMsg += "\n- "+displayName;
});
customAlert(multiMsg);
return false;
}
//check if javascript-variable exists > we need ctx to get the id of the sharepoint-list
if(ctx==null)
{
//this javascript-variable is essential for getting the list-id and the list-view-id.
customAlert("The javascript-variable 'ctx' does not exist within the html-dom. > Abort now!");
return false;
}
//all checks passed - return true
return true;
}
function BuildGoogleMapCustomLogForSharePointList()
{
if(showWarningAndErrorAlerts!=1)
{
return;
}
var divCustomLogOverview = '<div title="'+resxAlertsMessageTextTitle+'" onclick="ToggleCustomLog();" id="'+idOfCustomLogOverview+'" style="margin: 10px; cursor: pointer; color: red; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLogOverview);
var divCustomLog = '<div id="'+idOfCustomLogDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLog);
}
function ToggleCustomLog()
{
//show or hide
$("#"+idOfCustomLogDiv).toggle();
}
function ToggleGoogleMapDiv()
{
//check if the map will be called for the first time
if(!hasMapBeenLoadedInitially)
{
ShowGoogleMapForSharePointList();
}
//show or hide
$("#"+idOfMapDiv).toggle();
}
function BuildGoogleMapIconForSharePointList()
{
//searching for the correct position in the menu-toolbar (ms-menutoolbar)
$("td.ms-toolbar").each(function(j){
if($(this).attr("width")=="99%")
{
//insert a new menu-item before the found placeholder
//var newMenuItem = '</internal-name-of-column><td class="ms-separator">';
var newMenuItem = '<td class="ms-separator">';
newMenuItem += '<img src="/_layouts/images/blank.gif" alt=""/>';
newMenuItem += '</td>';
newMenuItem += '<td nowrap="true" class="ms-toolbar">';
newMenuItem += '<span title="'+resxGoogleMapsLinkTitle+'">';
newMenuItem += '<div nowrap="nowrap" hoverinactive="ms-menubuttoninactivehover" hoveractive="ms-menubuttonactivehover" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" class="ms-menubuttoninactivehover">';
newMenuItem += '<a onclick="javascript:ToggleGoogleMapDiv();return false;" href="#" style="cursor: pointer; white-space: nowrap;">'+resxGoogleMapsLink+'</a>';
newMenuItem += '</div>';
newMenuItem += '</span>';
newMenuItem += '</td>';
$(this).before(newMenuItem);
}
});
//adding map-canvas as div-tag to the dom
var divMapCanvas = '<div id="'+idOfMapDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().before(divMapCanvas);
//check if the map should be shown as soon as possible or if it should be hidden until the user clicked the new menu-point
if(!hideMapUntilClick)
{
ToggleGoogleMapDiv();
}
}
//gets the complete list-schema and one row with all its values (not filtered by the current used view)
function BuildAjaxRequestUrlForSharePointListByID_Template()
{
if(ctx!=null)
{
//build the url of the ajax-request
return ctx.HttpRoot+'/_vti_bin/owssvr.dll?XMLDATA=1&List=' + ctx.listName + '&Query=*&FilterField1='+colID+'&FilterValue1=';
}
}
//gets the list-schema and no rows
function BuildAjaxRequestUrlForSharePointListSchemaOnly()
{
//build the url of the ajax-request
return BuildAjaxRequestUrlForSharePointListByID_Template()+'-1';
}
function ShowGoogleMapForSharePointList()
{
//build the url of the ajax-request
var urlTemplate = BuildAjaxRequestUrlForSharePointListByID_Template();
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
//check if the number of geocodings will exceed the max-number
if(!useCoordinates && $(jQuerySelect_GetListRowByAttributeCTXName).length > noOfMaxGeocodingRequest)
{
var linkToStatusCodes = '<a title="Statuscodes of geocoding-responses from Google-Maps" target="_blank" href="http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/services.html#GeocodingStatusCodes">OVER_QUERY_LIMIT-Status</a>';
var tooManyMsg = "Hint: In the current view of the SharePoint-List there are more than "+noOfMaxGeocodingRequest+" list-entries. ";
tooManyMsg += "This will result in an "+linkToStatusCodes+" by Google-Maps (and not all markers will be shown on the map). > You have 2 options: ";
tooManyMsg += "a) Change your view to get no more than "+noOfMaxGeocodingRequest+" list-entries or ";
tooManyMsg += "b) use the coordinates (longitude, latitude) of the addresses (they will be shown on the map).";
customAlert(tooManyMsg);
}
//get each row from list-view which is shown at the moment
$(jQuerySelect_GetListRowByAttributeCTXName).each(function(j)
{
var lat, lng, gmLatLng, gmMarker, title, customUrl, street, city, country;
var idOfListItem = $(this).attr(colID);
if(isSharePoint2010)
{
var linkToListItem = '<table height="auto" width="calcWidthpx"><tr class="ms-alternating ms-itmhover"><td height="100%" class="ms-vb-title" onmouseover="OnChildItem(this)">';
linkToListItem += $(this).parent().html();
linkToListItem += '</td></tr></table><span style="font-size:72pt;"></br></span>';
}
else
{
linkToListItem = $(this).parent().html();
linkToListItem = linkToListItem.replace(/100%/g, "auto"); //exchange tag-attributes for width and height
}
//build url for the ajax-request which reads all data for a certain row (for the current list-view)
customUrl = urlTemplate+idOfListItem;
//get the data for the row
$.get(customUrl, {}, function (xml)
{
$('xml > *:last > *', xml).each(function (i)
{
//get some data from the xml-response
title = $(this).attr(colLinkTitleInternalName);
if(isSharePoint2010)
{
var titleLength= title.length+185;
linkToListItem = linkToListItem.replace('calcWidth', titleLength);
}
if(useCoordinates)
{
//getting coordinates
lat = $(this).attr(colLatitudeInternalName);
lng = $(this).attr(colLongitudeInternalName);
if(typeof(lat)!='undefined' && typeof(lng)!='undefined')
{
gmLatLng = new google.maps.LatLng(lat, lng);
msgForInfoWindow = linkToListItem; //you may add more information-text here
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
else
{
customAlert(title +" has undefined lat+lng. > Do not add marker on map.");
}
}
else
{
//getting address
street = $(this).attr(colStreetInternalName);
zip = $(this).attr(colZipInternalName);
city = $(this).attr(colCityInternalName);
country = $(this).attr(colCountryInternalName);
//checking received values
if(typeof(street)=='undefined') street = ""; //optional
if(typeof(zip)=='undefined') zip = ""; //optional
if(typeof(city)=='undefined')
{
customAlert("The ajax-response got no city for '"+title+"'. > Do not add marker on map.");
return;
}
if(typeof(country)=='undefined') country = defaultCountryValue;
address = street+","+zip+","+city+","+country;
//getting coordinates
gmGeocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
if(results.length==0)
{
customAlert("Geocoding: There are no results for address '"+results[0].formatted_address+"'! Expected exactly one result. > Do not show any marker on map for this address.");
}
else if(results.length>1)
{
var msg = "Geocoding: There are too many ("+results.length+") results for given address! Expected exactly one result. > Do not show any marker on map for this address.\n\nFound addresses:\n";
for(i=0;i<results.length;i++)
{
var c = i+1;
msg += "\n"+c+": "+results[i].formatted_address;
}
customAlert(msg);
}
else
{
gmLatLng = results[0].geometry.location;
var msgForInfoWindow = linkToListItem+"<br>";
msgForInfoWindow += "<span style='font-size:0.8em;'>Koordinaten (Lat, Lon): "+gmLatLng+"<br>Adresse: "+results[0].formatted_address+"</span>";
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
}
else
{
customAlert("Geocode for address '"+address+"' was not successful for the following reason: " + status);
}
});
}
});
});
});
hasMapBeenLoadedInitially = true;
}
function SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, contentForInfoWindow)
{
var gmMarker = new google.maps.Marker({
position: gmLatLng,
map: gmMap,
title: title,
zIndex: 0
});
gmBounds.extend(gmLatLng);
gmMap.setCenter(gmBounds.getCenter());
gmMap.fitBounds(gmBounds);
if(contentForInfoWindow!=null && contentForInfoWindow!="")
{
var gmInfowindow = new google.maps.InfoWindow({
content: contentForInfoWindow
});
google.maps.event.addListener(gmMarker, 'click', function() {
gmInfowindow.open(gmMap,gmMarker);
});
}
}
function customAlert(msg)
{
if(msg==null || msg=="")
{
return;
}
else
{
var now = new Date();
msg = now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+": "+msg;
}
if(showWarningAndErrorAlerts==0)
{
//do nothing
}
else if(showWarningAndErrorAlerts==1)
{
//do log in log-div
msg = msg.replace(/\n/g, "<br/>");
msg += "<br/><br/>";
$("#"+idOfCustomLogDiv).append(msg);
noOfCustomLogEntries++;
$("#"+idOfCustomLogOverview).show();
var overviewText = resxAlertsMessageText.replace(/#/g, noOfCustomLogEntries);
$("#"+idOfCustomLogOverview).text(overviewText);
}
else if(showWarningAndErrorAlerts==2)
{
//do alert via javascript-alert
alert(msg);
}
else
{
//unsupported
}
}
//call initialization after the dom has been loaded completely > so it does not matter where this piece of javascript will be inserted in the dom
$(document).ready(InitializeGoogleMapForSharePointList);</script>
Result in Chrome e Edge:
Screenshot
Just to put an answer to this question, adding the meta tag of <meta http-equiv="X-UA-Compatible" content="IE=8"> would solve the issue.

Call markers based on radio button value

I am trying to call markers to a google map based on a value (year as a string). I thought by putting an on click event to listen for when the radio class is clicked, that I could initialize the $.getJSON and set the value for the year.
How can initialize the $.getJSON call when the radio button is clicked and base the variable yearValue on which radio button is checked?
Also, if I wanted to reset the markers each time a new radio button is clicked, would I need to put all of the markers in an array, set them to the map, then clear the array when a new radio button value is checked (say I choose 2014 instead of 2015?). How can I clear the markers when a new radio button is checked so that I don't see both years at the same time?
var map;
var mapProp;
var url = 'https://data.montgomerycountymd.gov/resource/5pue-gfbe.json?$limit=50000';
var count;
var marker;
var manyCategory = [];
var category = [];
var yearValue;
function initMap() {
mapProp = {
center: new google.maps.LatLng(39.154743, -77.240515),
zoom: 10
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
}
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
}
$(document).ready(function() {
if ($('input:radio[name="year"]').is("checked")) {
yearValue = $(this).val();
}
initMap();
$('.radioClass').on('click', function() {
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < data.length; i++) {
var newDate = data[i].inspectiondate;
if (data[i].violation22 === "Out of Compliance" && newDate.slice(0, 4) === yearValue) {
if (data[i].hasOwnProperty('latitude')) {
count++;
var message = "<div>" + data[i].organization + "<br>" + (data[i].inspectiondate).slice(0, 10) + "</div>";
var uniqueIcon;
if (data[i].category === "Private School" || data[i].category === "Public School- Elementary" || data[i].category === "Public School- High" || data[i].category === "Public School- Middle") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/blue.png";
} else if (data[i].category === "Market" || data[i].category === "Carry Out" || data[i].category === "Snack Bar" || data[i].category === "Caterer" || data[i].category === "Restaurant") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/purple.png"
} else if (data[i].category === "Nursing Home" || data[i].category === "Hospital" || data[i].category === "Assisted Living") {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/red.png"
} else {
uniqueIcon = "https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png";
}
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude),
title: "Hello, world. I received a food violation in 2015",
animation: google.maps.Animation.DROP,
icon: uniqueIcon,
});
marker.setMap(map);
//console.log(data[i].inspectionresults);
addInfoWindow(marker, message);
manyCategory.push(data[i].category);
}
}
}
//;
$.each(manyCategory, function(i, el) {
if ($.inArray(el, category) === -1) category.push(el);
})
//console.log(count);
//console.log(manyCategory);
//console.log(category);
});
});
});
h1,
#icons,
#radioDiv {
text-align: center;
}
#map {
margin: 0 auto;
width: 700px;
height: 400px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<h1>Rodent Violations</h1>
<div id="radioDiv">
<input type="radio" name="year" value="2015" class="radioClass">2015
<input type="radio" name="year" value="2014" class="radioClass">2014
</div>
<div id="icons">
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/blue.png">School
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/purple.png">Restaurant
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/red.png">Healthcare
<img src="https://maps.gstatic.com/mapfiles/ms2/micons/yellow.png">All other
</div>
<div id="map"></div>
You need an array fo markers globally visibile that hold all the markers you create for let you clean them before you show the new markers.
var myMarkers
add the begin of the callback function clear the markers setting maps to null
$.getJSON(url, function(data) {
count = 0;
for (var i = 0; i < myMarkers.length; i++) {
myMarkers[i].setMap(null);
}
myMarkers = []; // empty the array
.......
popluate the myMArkers Array with all the marker you create
marker.setMap(map);
addInfoWindow(marker, message);
myMarkers.push(marker);

Google Maps Script error in Onion.js

This morning I just started getting a google maps script error.
Line: 0
Char: 0
Error: Script Error
Code: 0
URL:
I reverted all my code changes back to an earlier version but it still persists.
I will include the script below but I must mention that this runs in a Delphi TWebBrowser that interfaces IE.
I can run my program, interact with the Page and then let it sit idle. After 20 seconds or so, without any user interaction, I get the persistent error above. When I close the Error Message box, it immediately opens with the same message.
I have been working this project for months and now this started. I have rolled back several versions but it still persists.
Where do I start looking?
<html>
<head>
<title>Find your Qtr minute locator</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?api=AIzaSyAa7YZpvi09ig92s_BLP2H3QVLTmoqdcQQ&v=3.exp&libraries=geometry&sensor=false"></script>
</head>
<body><!-- Declare the div, make it take up the full document body -->
<div id="map-canvas" style="HEIGHT: 100%; WIDTH: 100%"></div>
<script type="text/javascript">
var map;
var idx = 0;
var qtrArray = [];
var userGridArray = [];
var Startlatlng = "";
var llOffset = 0.00416666666667;
var babyOffset = (llOffset/2); // offsets gridSelector 1/2 qtr min
var drawGridSelectBox = false;
var findNeighbor = false;
var firstRun = true;
var drawGridBox = false;
var deSelectOn = false;
var GridSelect = false;
var gridOverBox = new google.maps.Polygon();
var gridSelectBox = new google.maps.Polygon();
var gridline;
var polylinesquare;
var latPolylines = [];
var lngPolylines = [];
var lngLabels = [];
var otherColor = "#128A00";
var bounds = new google.maps.LatLngBounds();
function initialize() {
map = new google.maps.Map(document.getElementById("map-canvas"), {
center: new google.maps.LatLng(34.0, -84.0),
zoom: 14,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
});
google.maps.event.addListener(map, "click", function (event) {
if (!google.maps.geometry.poly.containsLocation(event.latLng, gridSelectBox)) {
map.setZoom(14);
if (findNeighbor)
MarkArea(event.latLng.lat(), event.latLng.lng());
if (drawGridSelectBox) {
createGridSelectBox(event.latLng);
GridSelect = !firstRun;
if (!GridSelect) {
ClearGrid()
}
}
for(var xx=0;xx<latPolylines.length;++xx){
for(var yy=0;yy<lngPolylines.length-1;++yy){
var latLng=new google.maps.LatLng(latPolylines[xx].getPath().getAt(0).lat(),
lngPolylines[yy].getPath().getAt(0).lng());
if ((google.maps.geometry.poly.containsLocation(latLng, gridSelectBox))&&(!firstRun))
{
drawGridBox = true;
createGridBox(latLng);
}
}
}
firstRun = false;
map.panTo(event.latLng);
drawGridBox = false;
}});
DrawGridOn();
google.maps.event.addListener(map, "idle", function () {
createGridLines(map.getBounds());
});
} // initialize
google.maps.event.addDomListener(window, "load", initialize);
function createGridLines(bounds) {
for (var i = 0; i < latPolylines.length; i++) {
latPolylines[i].setMap(null);
}
latPolylines = [];
for (var j = 0; j < lngPolylines.length; j++) {
lngPolylines[j].setMap(null);
}
lngPolylines = [];
for (var k = 0; k < lngLabels.length; k++) {
lngLabels[k].setMap(null);
}
lngLabels = [];
if (map.getZoom() < 10) return;
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
// define the size of the grid
var topLat = Math.ceil(north / llOffset) * llOffset;
var rightLong = Math.ceil(east / llOffset) * llOffset;
var bottomLat = Math.floor(south / llOffset) * llOffset;
var leftLong = Math.floor(west / llOffset) * llOffset;
var qtrNELatLngCode = ddToQM(topLat, rightLong);
var qtrNorth = qtrNELatLngCode.substring(0, 5);
var qtrEast = qtrNELatLngCode.substring(5, 12);
var qtrSWLatLngCode = ddToQM(bottomLat, leftLong);
var qtrSouth = qtrSWLatLngCode.substring(0, 5);
var qtrWest = qtrSWLatLngCode.substring(5, 12);
for (var latitude = bottomLat; latitude <= topLat; latitude += llOffset) latPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(latitude, leftLong), new google.maps.LatLng(latitude, rightLong)],
map: map,
geodesic: true,
strokeColor: "#0000FF",
strokeOpacity: 0.1,
strokeWeight: 1
}));
for (var longitude = leftLong; longitude <= rightLong; longitude += llOffset) lngPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(topLat, longitude), new google.maps.LatLng(bottomLat, longitude)],
map: map,
geodesic: true,
strokeColor: "#0000FF",
strokeOpacity: 0.1,
strokeWeight: 1
}));
if (map.getZoom() < 15) {
for (var l = 0; l < lngLabels.length; l++) {
lngLabels[l].setMap(null);
}
lngLabels = [];
return;
} // set lngLabels to null
for(var x=0;x<latPolylines.length;++x){
for(var y=0;y<lngPolylines.length-1;++y){
var latLng=new google.maps.LatLng(latPolylines[x].getPath().getAt(0).lat(),
lngPolylines[y].getPath().getAt(0).lng());
var qtrLatLng = ddToQM(latLng.lat(), latLng.lng());
lngLabels.push(new google.maps.Marker({
map:map,
position:latLng,
icon:{ url:"https://chart.googleapis.com/chart?"
+"chst=d_bubble_text_small&chld=bb|"
+ qtrLatLng
+"|FFFFFF|000000",
anchor:new google.maps.Point(0,42)
}
}));
}
}
external.ShowQtrMinBounds(qtrNorth, qtrSouth, qtrEast, qtrWest);
} // end createGridLines
function createGridSelectBox(point) {
// Square limits
var smPoint = point;
var bottomLeftLat = (Math.floor(point.lat() / llOffset) * llOffset) - babyOffset;
var bottomLeftLong = (Math.floor(point.lng() / llOffset) * llOffset) - babyOffset;
var gridLineSquare = [
new google.maps.LatLng(bottomLeftLat, bottomLeftLong), //lwr left
new google.maps.LatLng(bottomLeftLat, bottomLeftLong + llOffset), //lwr right
new google.maps.LatLng(bottomLeftLat + llOffset, bottomLeftLong + llOffset), //upr right
new google.maps.LatLng(bottomLeftLat + llOffset, bottomLeftLong)]; //upr left
//auto-complete to lwr left
if (drawGridSelectBox == true) {
gridSelectBox = new google.maps.Polygon({
path: gridLineSquare,
draggable:true,
geodesic:true,
editable :true,
fillColor: "#FF0000",
fillOpacity: 0.35,
strokeColor: "#CC0099",
strokeOpacity: 0.1,
strokeWeight: 1
});
gridSelectBox.setMap(map);
drawGridSelectBox = false;
}
}
function MarkArea(Lat, Lng) {
var latLng = new google.maps.LatLng(Lat,Lng);
drawUserGrids(latLng);
}
function SaveQtrMin(){
for (var m in qtrArray) {
external.SaveQtrMinutes(qtrArray[m].qtrMinute);
}
}
function DrawGridOn() { //creates GridSelectBox
addGridOn = false;
drawGridSelectBox = true;
firstRun = true;
}
function DrawGridOff() {
gridSelectBox.setMap(null);
drawGridSelectBox = false;
}
function GotoLatLng(Lat, Lng) {
var latlng = new google.maps.LatLng(Lat,Lng);
map.setCenter(latlng);
}
function DeSelectOn(){
deSelectOn = true;
addGridOn = false;
}
function DeSelectOff(){ // Allows removing 1 QtrMin
deSelectOn = false;
}
function AddGridOn(){ // Allows adding 1 QtrMin
addGridOn = true;
deSelectOn = false;
}
function AddGridOff(){
addGridOn = false;
}
function ClearGrid() {
if (qtrArray) {
for (var i in qtrArray) {
qtrArray[i].setMap(null);
}
}
qtrArray=[];
idx = 0;
}
function ClearUserGrid() {
if (userGridArray) {
for (var i in userGridArray) {
userGridArray[i].setMap(null);
}
}
userGridArray=[];
}
function drawUserGrids(point) {
// Square limits
var bottomLeftLat = (Math.floor(point.lat() / llOffset) * llOffset);
var bottomLeftLong = (Math.floor(point.lng() / llOffset) * llOffset);
var gridLineSquare = [
new google.maps.LatLng(bottomLeftLat, bottomLeftLong), //lwr left
new google.maps.LatLng(bottomLeftLat, (bottomLeftLong + llOffset)), //lwr right
new google.maps.LatLng((bottomLeftLat + llOffset), (bottomLeftLong + llOffset)), //upr right
new google.maps.LatLng((bottomLeftLat + llOffset), bottomLeftLong)]; //upr left
drawGridBox = true;
if (drawGridBox == true) {
gridUserArea = new google.maps.Polygon({
path: gridLineSquare,
draggable:false,
geodesic:true,
editable :false,
fillColor:otherColor,
fillOpacity: 0.35,
strokeColor: "#CC0099",
strokeOpacity: 0.1,
strokeWeight: 1
});
gridUserArea.setMap(map);
userGridArray.push(gridUserArea);
}
}
function createGridBox(point) {
// Square limits
var arrayIdx = 0;
var addListenersOnPolygon = function(polygon) {
google.maps.event.addListener(polygon, 'click', function (event) {
if (deSelectOn==true) {
arrayIdx = qtrArray.indexOf(polygon);
qtrArray.splice(arrayIdx,1);
polygon.setMap(null);
}
});
};
var smPoint = point;
var bottomLeftLat = (Math.floor(point.lat() / llOffset) * llOffset);
var bottomLeftLong = (Math.floor(point.lng() / llOffset) * llOffset);
var gridLineSquare = [
new google.maps.LatLng(bottomLeftLat, bottomLeftLong), //lwr left
new google.maps.LatLng(bottomLeftLat, (bottomLeftLong + llOffset)), //lwr right
new google.maps.LatLng((bottomLeftLat + llOffset), (bottomLeftLong + llOffset)), //upr right
new google.maps.LatLng((bottomLeftLat + llOffset), bottomLeftLong)]; //upr left
drawGridBox = true;
if (drawGridBox == true) {
gridOverBox = new google.maps.Polygon({
path: gridLineSquare,
draggable:false,
geodesic:true,
editable :false,
fillColor: "#EAED00",
fillOpacity: 0.35,
strokeColor: "#CC0099",
strokeOpacity: 0.1,
strokeWeight: 1,
qtrMinute : ddToQM(bottomLeftLat, bottomLeftLong),
indexID : ++idx
});
gridOverBox.setMap(map);
addListenersOnPolygon(gridOverBox);
qtrArray.push(gridOverBox);
}
}
function ddToQM(alat, alng) {
var latResult, lngResult, dmsResult;
alat = parseFloat(alat);
alng = parseFloat(alng);
latResult = "";
lngResult = "";
latResult += getDms(alat);
lngResult += getDms(alng);
dmsResult = latResult + lngResult;
// Return the resultant string.
return dmsResult;
}
function toggleGridSelection(){
GridSelect = true;//(!!GridSelect);
}
function findNeighborOn(){
findNeighbor = true;
otherColor = randColor();
}
function findNeighborOff(){
findNeighbor = false;
otherColor = "#128A00";
}
function randColor() {
var i;
var colorArray = ["#B2A209","#A4A07B","#B02600","#6CA200","#BC0072","#B1ADFF","#16CADB","#A1FFD1","#9999CC","#EEFF7C"];
i = Math.floor((Math.random() *10)+1);
return colorArray[i];
}
function getDms(val) {
// Required variables
var valDeg, valMin, valSec, interimResult;
var qtrMin;
val = Math.abs(val);
// ---- Degrees ----
valDeg = Math.floor(val);
valMin = Math.floor((val - valDeg) * 60);
valSec = Math.round((val - valDeg - valMin / 60) * 3600 * 1000) / 1000;
if (valSec == 60){
valMin +=1;
valSec = 0;
}
if (valMin == 60){
valMin +=1;
valSec = 0;
}
interimResult = valDeg+"";
if (valMin<10){
valMin = "0"+valMin;
}
interimResult += valMin + "";
switch(valSec){
case 0 : qtrMin = "A";
break;
case 15 : qtrMin = "B";
break;
case 30 : qtrMin = "C";
break;
case 45 : qtrMin = "D";
break;
}
interimResult += qtrMin;
return interimResult;
}
</script>
</body>
</html>
Adding the following meta tag in a header section solved this issue for me.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
The X-UA-Compatible meta tag allows web authors to choose what
version of Internet Explorer the page should be rendered as.
Edge mode tells Internet Explorer to display content in the highest mode
available.
I also changed this tag. then work it well. thanks
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
It works both ver 3.22 & 3.23.
This onion.js script error has returned, the v=3.22 no longer fixes the issue. It turns out that the problem is an issue with IE and onios.js. Embedding a web browser by default used IE7 standard and that’s the problem my fix was an addition to the registry as follows:-
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"yourApp.exe"=dword:00002EDF
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"yourApp.exe"=dword:00002EDF
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"yourApp.exe"=dword:00002EDF
Google launched a new release version 3.24 on May 24, 2016.
According to the versioning model, there are only three versions: frozen, release and experimental.
https://developers.google.com/maps/documentation/javascript/versions
Version 3.22 is retired and cannot be accessed anymore.
The new version supports only IE10 and IE11, the compatibility mode is unsupported.
https://developers.google.com/maps/documentation/javascript/browsersupport
WebBrowser control can default to an IE 7 rendering mode:
https://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version
You should force the control to a newer IE version
http://www.codeproject.com/Articles/793687/Configuring-the-emulation-mode-of-an-Internet-Expl
Use latest version of Internet Explorer in the webbrowser control
Additionally, you can add the meta tag in your html
It looks like the new version of Maps JavaScript API relies on a global JSON object which is not available in IE7. So, alternatively you can try to polyfill JSON:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
I was having the same error.
I've just found a solution that worked for me.
I just added "&v=3.22" in the url of Google Maps.
Like this:
http://maps.google.com/maps/api/js?sensor=true&v=3.22
I was having a similar problem and the provided solution didn't work for me. I was getting the error in Delphi inside the TWebBrowser control also with the meta tag.
I figured out the problem.
Onion.js fires the error, because it calls JSON.parse.
JSON Parse isn't supported by the web browser control. You can test this by adding this to your JavaScript (already quoted for Delphi):
'var code = ''"\u2028\u2029"''; JSON.parse(code); ' +
Every browser should execute
var code = '"\u2028\u2029"';
JSON.parse(code);
When executed in Delphi it fires an error instantly.
You can avoid the whole thing with a JSON3 polyfill (already quoted for Delphi):
'<script src="https://cdn.jsdelivr.net/json3/3.3.2/json3.js"></script>' +
Then JSON will be defined and work as expected, resolving the problem.

Blogger API not retrieving all the post from a blog

I have a travel blog with blogspot. I have a page which displays a map of the world with the path taken so far. To do this, I use the blogger API to retrieve the location of each post as follow:
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
My issue is that it seems that only the last posts are retrieved and the first ones ignored. On the following link, the complete path should contain all the south of Argentina and be linked to the current path shown.
http://el-gato-lindo.blogspot.com/p/map.html
The complete code to generate the map is as follow:
<html>
<body>
<div id="content">
</div>
<div align="center" id="googleMap" style="height: 900px; width: 620px;">
</div>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>
<script>
var Lat = new Array();
var Lng = new Array();
var Place = new Array();
var TitlePost = new Array();
var UrlPost = new Array();
var DatePost = new Array();
// Get latitude/longitude from Blogger
function handleResponse(response) {
for(i=0; i< response.items.length; i++){
if(response.items[i].location != undefined){
Lat.push(response.items[i].location.lat);
Lng.push(response.items[i].location.lng);
Place.push(response.items[i].location.name);
TitlePost.push(response.items[i].title);
UrlPost.push(response.items[i].url);
DatePost.push(response.items[i].published);
}
}
}
// Distance btw two places in km
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1,p2)/1000).toFixed(2);
}
// Name of months for date formatting
var m_names = new Array();
m_names.push("January");
m_names.push("February");
m_names.push("March");
m_names.push("April");
m_names.push("May");
m_names.push("June");
m_names.push("July");
m_names.push("August");
m_names.push("September");
m_names.push("October");
m_names.push("November");
m_names.push("December");
// Create the map based on locations retrieved from Blogger
function initialize(){
// Get all latitude and longitude
var pos = new Array();
// Get the path
for(var i=0; i<Lat.length; i++){
pos[i]=new google.maps.LatLng(Lat[i],Lng[i]);
}
// Get the last position
var lastpos=new google.maps.LatLng(Lat[0],Lng[0]);
// Create the map
var mapProp = {
center:lastpos,
zoom:4,
mapTypeId:google.maps.MapTypeId.TERRAIN,
navigationControl:true,
streetViewControl:false
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
// Create the path
var flightPath = new google.maps.Polyline({
path:pos,
strokeColor:"#EE0000",
strokeOpacity:0.6,
strokeWeight:7,
clickable:false,
map:map
});
// Create invisible marker at each destination
var markerPos = new Array();
var infowindow = null;
for(var i=0; i<pos.length; i++){
marker=new google.maps.Marker({
position:pos[i],
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale:5,
fillOpacity:0,
strokeOpacity:0
},
clickable:true,
map:map
});
// Click on marker: Show infowindow with articles
google.maps.event.addListener(marker, 'click', function() {
// Articles posted within a given distance from point clicked will be shown
var toldist = 2048 / Math.pow(2,map.zoom); //km
str = '<div id="infowindow_listposts">';
for(var j=0; j<pos.length; j++){
if(pos[j] === this.position){
var optplace = j;
str += "<h1>
" + Place[j] + "</h1>
<br>";
}
}
str += "<ul>";
for(var j=0; j<pos.length; j++){
var dist = calcDistance(pos[j],this.position);
if(dist < toldist){
date = new Date(DatePost[j]);
str += "<li> <h2>
<a href='" + UrlPost[j] + "'>" + TitlePost[j] + "</a> <i>(";
str += m_names[date.getMonth()] + " " + date.getDate() + ", ";
str += date.getFullYear() + ") </i></h2>
</li>
";
}
}
str += "</ul>
";
str += "<i> Articles shown were written less than ";
if(toldist >= 1)
str += toldist + "km away from ";
else
str += 1000*toldist + "m away from ";
str += Place[optplace] + ".</i>";
str += "</div>
";
if (infowindow){
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content:str
});
infowindow.open(map,this);
});
markerPos.push(marker);
}
// Create the marker of last position
var lastmarker=new google.maps.Marker({
position:lastpos,
clickable:false,
map:map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
</script>
</body>
</html>
Thanks a lot for your help! I am currently travelling and it is quite difficult to solve this issue!
Nicolas
Try replacing
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">
with
<script src="https://www.googleapis.com/blogger/v3/blogs/3089072491354463482/posts/default?redirect=false&start-index=1&max-results=500?callback=handleResponse&key=AIzaSyAJO5J-pRCaGOIeRLIJfvAPwxpMLKvwebU">

Google Map Integrated with Salesforce is Blank

I followed the example code line by line from:
How do I integrate Salesforce with Google Maps?
I am not receiving any errors but my Map is blank. The map displays the zoom and position toggle but nothing else.
Any ideas on why?
Here is my Controller Code and Page Code Below
public class mapController2 {
public String address {get;set;}
private List<Account> accounts;
public void find() {
// Normal, ugly query.
/* address = 'USA';
String addr = '%' + address + '%';
accounts = [SELECT Id, Name, BillingStreet, BillingCity, BillingCountry FROM Account
//WHERE Name LIKE :addr OR BillingStreet LIKE :addr OR BillingCity LIKE :addr OR BillingCountry LIKE :addr];
WHERE BillingCountry LIKE :addr];*/
// address = 'Austin';
String addr = '*' + address + '*';
// Or maybe a bit better full-text search query.
List<List<SObject>> searchList = [FIND :addr IN ALL FIELDS RETURNING
Account (Id, Name, BillingStreet, BillingCity, BillingState, BillingCountry)];
accounts = (List<Account>)searchList[0];
}
public List<Account> getAccounts() {
return accounts;
}
}
Page Code
<apex:page controller="mapController2" tabStyle="Account">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
#map {
height:350px;
}
</style>
</head>
<apex:form >
<apex:pageBlock title="Search by Address">
<apex:inputText value="{!address}"/>
<apex:commandButton value="Search" action="{!find}"/>
<p>Examples: "USA", "Singapore", "Uni", "(336) 222-7000".
Any text data (free text, not picklists, checkboxes etc.) will do.
</p>
</apex:pageBlock>
<apex:pageBlock title="Matching Accounts" rendered="{!address != null}">
<apex:pageBlockTable value="{!accounts}" var="account" id="accountTable">
<apex:column >
<apex:facet name="header"><b>Name</b></apex:facet>
<apex:outputLink value="../{!account.Id}">{!account.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header"><b>Address</b></apex:facet>
{!account.BillingStreet}, {!account.BillingCity}, {!account.BillingCountry}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title="Map" rendered="{!address != null}">
<div id="log"></div>
<p>Tip: hover mouse over marker to see the Account name. Click to show the baloon.</p>
<div id="map">Placeholder - map will be created here.</div>
<script type="text/javascript">
// First we need to extract Account data (name and address) from HTML into JavaScript variables.
var names = new Array();
var addresses = new Array();
var htmlTable = document.getElementById('j_id0:j_id2:j_id7:accountTable').getElementsByTagName("tbody")[0].getElementsByTagName("tr");
for (var i = 0; i < htmlTable.length; ++i) {
names.push(htmlTable[i].getElementsByTagName("td")[0]);
// We need to sanitize addresses a bit (remove newlines and extra spaces).
var address = htmlTable[i].getElementsByTagName("td")[1].innerHTML;
addresses.push(address.replace(/\n/g, "").replace(/^\s+/,"").replace(/\s+$/,""));
}
var coordinates = new Array(); // Array of latitude/longitude coordinates.
var markers = new Array(); // Red things we pin to the map.
var baloons = new Array(); // Comic-like baloons that can float over markers.
var counter = 0;
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
if(addresses.length > 0) {
geocodeOneAddress();
}
function geocodeOneAddress(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: addresses[counter]}, processGeocodingResults);
}
function processGeocodingResults(results, status) {
++counter;
if (status == google.maps.GeocoderStatus.OK) {
coordinates.push(results[0].geometry.location);
} else {
logError(addresses[counter] + " could not be found, reason: " + status);
}
if(counter == addresses.length) {
finalizeDrawingMap();
} else {
geocodeOneAddress();
}
}
function finalizeDrawingMap() {
// Compute min/max latitude and longitude so we know where is the best place to center map & zoom.
var minLat = coordinates[0].b;
var maxLat = coordinates[0].b;
var minLong = coordinates[0].c;
var maxLong = coordinates[0].c;
for(i=0;i < coordinates.length; i++){
markers.push(new google.maps.Marker({ position: coordinates[i], map: map, title: names[i].getElementsByTagName("a")[0].innerHTML, zIndex:i}));
baloons.push(new google.maps.InfoWindow({content: '<b>'+names[i].innerHTML + '</b><br/>' + addresses[i]}));
google.maps.event.addListener(markers[i], 'click', function() {
baloons[this.zIndex].open(map,this);
});
minLat = Math.min(minLat, coordinates[i].b);
maxLat = Math.max(maxLat, coordinates[i].b);
minLong = Math.min(minLong, coordinates[i].c);
maxLong = Math.max(maxLong, coordinates[i].c);
}
map.setCenter(new google.maps.LatLng(minLat + (maxLat-minLat) / 2, minLong + (maxLong-minLong) / 2));
// All that is left is to possibly change the zoom. Let us compute the size of our rectangle.
// This is just a rough indication calculation of size of rectangle that covers all addresses.
var size = (maxLat-minLat) * (maxLong-minLong);
var zoom = 13;
if(size > 7100) {
zoom = 2;
}
else if(size > 6000) {
zoom = 3;
}
else if(size > 550) {
zoom = 4;
}
else if(size > 20) {
zoom = 6;
}
else if(size > 0.12) {
zoom = 9;
}
map.setZoom(zoom);
}
function logError(msg) {
var pTag = document.createElement("p");
pTag.innerHTML = msg;
document.getElementById('log').appendChild(pTag);
}
</script>
</apex:pageBlock>
</apex:form>
</apex:page>
Ya even I was getting a blank map but try to do
https://c.na3.visual.force.com/apex/map?id=0015000000UsQZR
Make sure you enter a valid account id to use.
<apex:page standardController="Account">
<script src="http://maps.google.com/maps?file=api">
</script>
<script type="text/javascript">
var map = null;
var geocoder = null;
var address = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";
function initialize() {
if(GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("MyMap"));
map.addControl(new GMapTypeControl());
map.addControl(new GLargeMapControl3D());
geocoder = new GClientGeocoder();
geocoder.getLatLng(
address,
function(point) {
if (!point) {
document.getElementById("MyMap").innerHTML = address + " not found";
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.bindInfoWindowHtml("Account Name : <b><i> {!Account.Name} </i></b>
Address : "+address);
}
}
);
}
}
</script>
<div id="MyMap" style="width:100%;height:300px"></div>
<script>
initialize() ;
</script>
</apex:page>
Hope this helps
Thanks
tosha
And use the code given as:
src="http://maps.google.com/maps/api/js?sensor=false"
Use
https
not
http
It will definately be blank in firefox or chrome if using http and not https. Try https.