Google Map Integrated with Salesforce is Blank - google-maps

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.

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.

Google maps api v3 calculate mileage by state

I'm searching for a way to calculate mileage by US State based on an origin, waypoints and destination of a route using Google Maps API v3.
I have tried using Googles Distance Matrix API but this it is calculating the distance between 2 points, which is good, but I need the break down for miles traveled for each State. For taxes purposes (IFTA reports for transportation).
I've done a lot of googling and looked through the documentation but I'm not seeing anything that calculate the mileage per State.
I know how to use Google maps and I know this is possible since I saw it on one video. There is no code I can show because I have no idea how to do it. Any thoughts?
Useful links I have found:
How to Draw Routes and Calculate Route Time and Distance on the Fly Using Google Map API V3 http://www.c-sharpcorner.com/UploadFile/8911c4/how-to-draw-routes-and-calculate-route-time-and-distance-on/
How to Build a Distance Finder with Google Maps API http://www.1stwebdesigner.com/distance-finder-google-maps-api/
Below is a fully functional implementation that uses the Google Maps Javascript API. All you need to add is your own Maps API Key. As noted in the posts referenced above, Google Maps throttles requests at an asymptotic rate, and thus, the longer the route, the longer it will take to calculate. To give a ballpark, a route from New Haven CT to the NJ/PA border takes approximately 5 minutes. A trip from New Haven CT to Los Angeles takes 45 minutes to index. One other note: There are a few state borders that run through bodies of water. Google considers these to be not located in any state, and so reports undefined as the state name. These sections are obviously only a few tenths of a mile in most cases, but I felt I should mention it just to clarify what is going on when that happens.
UPDATED:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-KEY-HERE>"></script>
<div id="map" style="height:400px"></div>
<div id="status"></div>
<div id="results" style="height:400px"><b>Results:</b></div>
<script>
var directionsRequest = {
origin: "New York, NY", //default
destination: "Los Angeles, LA", //default
optimizeWaypoints: true,
provideRouteAlternatives: false,
travelMode: google.maps.TravelMode.DRIVING,
drivingOptions: {
departureTime: new Date(),
trafficModel: google.maps.TrafficModel.PESSIMISTIC
}
};
directionsRequest.origin = prompt("Enter your starting address");
directionsRequest.destination = prompt("Enter your destination address");
var starttime = new Date();
var geocoder = new google.maps.Geocoder();
var startState;
var currentState;
var routeData;
var index = 0;
var stateChangeSteps = [];
var borderLatLngs = {};
var startLatLng;
var endLatLng;
directionsService = new google.maps.DirectionsService();
directionsService.route(directionsRequest, init);
function init(data){
routeData = data;
displayRoute();
startLatLng = data.routes[0].legs[0].start_location;
endLatLng = data.routes[0].legs[0].end_location;
geocoder.geocode({location:data.routes[0].legs[0].start_location}, assignInitialState)
}
function assignInitialState(data){
startState = getState(data);
currentState = startState;
compileStates(routeData);
}
function getState(data){
for (var i = 0; i < data.length; i++) {
if (data[i].types[0] === "administrative_area_level_1") {
var state = data[i].address_components[0].short_name;
}
}
return state;
}
function compileStates(data, this_index){
if(typeof(this_index) == "undefined"){
index = 1;
geocoder.geocode({location:data.routes[0].legs[0].steps[0].start_location}, compileStatesReceiver);
}else{
if(index >= data.routes[0].legs[0].steps.length){
console.log(stateChangeSteps);
index = 0;
startBinarySearch();
return;
}
setTimeout(function(){
geocoder.geocode({location:data.routes[0].legs[0].steps[index].start_location}, compileStatesReceiver);
$("#status").html("Indexing Step "+index+"... ("+data.routes[0].legs[0].steps.length+" Steps Total)");
}, 3000)
}
}
function compileStatesReceiver(response){
state = getState(response);
console.log(state);
if(state != currentState){
currentState = state;
stateChangeSteps.push(index-1);
}
index++;
compileStates(routeData, index);
}
var stepIndex = 0;
var stepStates = [];
var binaryCurrentState = "";
var stepNextState;
var stepEndState;
var step;
var myLatLng = {lat:39.8282, lng:-98.5795};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
function displayRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setDirections(routeData);
}
var orderedLatLngs = [];
function startBinarySearch(iterating){
if(stepIndex >= stateChangeSteps.length){
for(step in borderLatLngs){
for(state in borderLatLngs[step]){
for(statename in borderLatLngs[step][state]){
$("#results").append("<br>Cross into "+statename+" at "+JSON.stringify(borderLatLngs[step][state][statename], null, 4));
orderedLatLngs.push([borderLatLngs[step][state][statename], statename]);
}
}
}
compileMiles(true);
return;
}
step = routeData.routes[0].legs[0].steps[stateChangeSteps[stepIndex]];
console.log("Looking at step "+stateChangeSteps[stepIndex]);
borderLatLngs[stepIndex] = {};
if(!iterating){
binaryCurrentState = startState;
}
geocoder.geocode({location:step.end_location},
function(data){
if(data === null){
setTimeout(function(){startBinarySearch(true);}, 6000);
}else{
stepNextState = getState(data);
stepEndState = stepNextState;
binaryStage2(true);
}
});
}
var minIndex;
var maxIndex;
var currentIndex;
function binaryStage2(init){
if (typeof(init) != "undefined"){
minIndex = 0;
maxIndex = step.path.length - 1;
}
if((maxIndex-minIndex)<2){
borderLatLngs[stepIndex][maxIndex]={};
borderLatLngs[stepIndex][maxIndex][stepNextState]=step.path[maxIndex];
var marker = new google.maps.Marker({
position: borderLatLngs[stepIndex][maxIndex][stepNextState],
map: map,
});
if(stepNextState != stepEndState){
minIndex = maxIndex;
maxIndex = step.path.length - 1;
binaryCurrentState = stepNextState;
stepNextState = stepEndState;
}else{
stepIndex++;
binaryCurrentState = stepNextState;
startBinarySearch(true);
return;
}
}
console.log("Index starts: "+minIndex+" "+maxIndex);
console.log("current state is "+binaryCurrentState);
console.log("next state is "+ stepNextState);
console.log("end state is "+ stepEndState);
currentIndex = Math.floor((minIndex+maxIndex)/2);
setTimeout(function(){
geocoder.geocode({location:step.path[currentIndex]}, binaryStage2Reciever);
$("#status").html("Searching for division between "+binaryCurrentState+" and "+stepNextState+" between indexes "+minIndex+" and "+maxIndex+"...")
}, 3000);
}
function binaryStage2Reciever(response){
if(response === null){
setTimeout(binaryStage2, 6000);
}else{
state = getState(response)
if(state == binaryCurrentState){
minIndex = currentIndex +1;
}else{
maxIndex = currentIndex - 1
if(state != stepNextState){
stepNextState = state;
}
}
binaryStage2();
}
}
var currentStartPoint;
var compileMilesIndex = 0;
var stateMiles = {};
var trueState;
function compileMiles(init){
if(typeof(init)!= "undefined"){
currentStartPoint = startLatLng;
trueState = startState;
}
if(compileMilesIndex == orderedLatLngs.length){
directionsRequest.destination = endLatLng;
}else{
directionsRequest.destination = orderedLatLngs[compileMilesIndex][0];
}
directionsRequest.origin = currentStartPoint;
currentStartPoint = directionsRequest.destination;
directionsService.route(directionsRequest, compileMilesReciever)
}
function compileMilesReciever(data){
if(data===null){
setTimeout(compileMiles, 6000);
}else{
if(compileMilesIndex == orderedLatLngs.length){
stateMiles[stepEndState]=data.routes[0].legs[0].distance["text"];
$("#results").append("<br><br><b>Distances Traveled</b>");
for(state in stateMiles){
$("#results").append("<br>"+state+": "+stateMiles[state]);
}
var endtime = new Date();
totaltime = endtime - starttime;
$("#results").append("<br><br>Operation took "+Math.floor(totaltime/60000)+" minute(s) and "+(totaltime%60000)/1000+" second(s) to run.");
return;
}else{
stateMiles[trueState]=data.routes[0].legs[0].distance["text"];
}
trueState = orderedLatLngs[compileMilesIndex][1];
compileMilesIndex++;
setTimeout(compileMiles, 3000);
}
}
</script>
</script>

Google is undefined in infobox.js

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.

Google Map API functioning but not showing in IE and Firefox?

I am creating a responsive website in dreamweaver.
I have created a Google Maps API that allows users to type in their post code in a separate div and then click submit. The Google map div then shows driven route directions to a companies address. The Javascript functionality works fine in all browsers as you can see the blue line from one destination to another in the map area, however, in Chrome and Firefox the actual google map doesn't show and instead all you can see is a grey box.
Here is my Javascript inside the head tag:
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" /script
script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAHAfYOHY89NVUq-1CyGVzgBTPNatzWJGbQM8FMoJ2lMODanrQmxTwvcZlK0Uc4OEGRhhBcmvde8jn0w" /script
script type="text/javascript"
var map = null; // Hold global map var
var directions = null;
var geocoder = null;
var address = "Unit 4 Northgate Business Centre, Crown Road, EN1 1TG, UK";
var noticeFx;
$(document).ready(function(){
map = new GMap2(
document.getElementById("googlemap")
);
geocoder = new GClientGeocoder();
geocoder.getLatLng(address, addressFound);
directions = new GDirections(map);
GEvent.addListener(directions, "load", directionsLoaded);
GEvent.addListener(directions, "error", directionsNotLoaded);
map.setUIToDefault();
// Show directions on click
$('#Shaker').click(function(){
hideError();
var postcode = $('#MyPosition').val();
if(postcode == ''){
displayError('Please supply your starting location');
return false;
}
query = "from: " + postcode + ", UK to: " + address;
directions.load(query, {
"locale": "en_GB",
'travelMode': G_TRAVEL_MODE_DRIVING
});
return false;
});
});
function reduceMap(){ }
function enlargeMap(){ }
function hideDirections(){ }
function showDirections() {
$('directions-holder').tween.delay(500, $('directions-holder'), ['width', 900]);
}
function directionsLoaded(){
//showDirections();
}
function directionsNotLoaded(){
displayError('Could not locate your starting point');
}
function addressFound(point){
var iiIcon1 = new GIcon();
iiIcon1.image = 'images/marker.png';
iiIcon1.iconSize = new GSize(55, 48);
iiIcon1.iconAnchor = new GPoint(15, 33);
var iiIcon = new GIcon();
iiIcon.image = 'images/marker.png';
iiIcon.iconSize = new GSize(27, 48);
iiIcon.iconAnchor = new GPoint(15, 33);
var marker = new GMarker(point, iiIcon1, true);
var marker2 = new GMarker(point, iiIcon, true);
map.addOverlay(marker);
map.addOverlay(marker2);
map.setCenter(point, 16);
}
function displayError(msg){
$('#notice').html(msg);
$('#notice').show(500);
}
function hideError(msg){
$('#notice').hide();
}
</script>
Here is my html markup for the map:
div id="googlemap"
Here is my css styling for #googlemap:
#googlemap {
width:50%;
height:400px;
border-radius: 5px;
margin: 15px 0 0 0;
}

Weird Google Maps V2 Marker issue

Got this code, that only works when alert (markers.length); is uncommented.
When this javascript alert not shown I dont get any Markers.. Really weird!!
In the body tag I have <body onload="load()" onunload="GUnload()">
Previoslly the load() function is called and other functions :
function showAddress(address) {
if (geocoder) {//+', '+init_street
geocoder.getLatLng(address,
function(point) {
if (!point) {
document.getElementById("place").value="not found";
//alert(address + " not found");
} else {
// document.getElementById("place").value=point.y.toFixed(4) + "," + point.x.toFixed(4);
map.setCenter(point, 16);
marker.setPoint(point);
//marker.openInfoWindowHtml(address);
}
}
);
}
}
//from a point returns and address!
function showPointAddress(response) {
if (!response || response.Status.code != 200) {//not found
//alert("Status Code:" + response.Status.code);
document.getElementById("place").value="not found";
}
else {//found
map.setCenter(marker.getPoint(), 16);
place = response.Placemark[0];
document.getElementById("place").value=place.address;
//document.getElementById("place").value=marker.getPoint().toUrlValue();
}
}
// Creates a marker at the given point with the given number icon and text
function createMarker(p,text) {
var marker = new GMarker(p);
if (text!=""){
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);});
}
return marker;
}
` var geocoder = null;`
` var map = null;`
function load() {//loading the map
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.enableScrollWheelZoom();
geocoder = new GClientGeocoder();
if (init_street!=""){
geocoder.getLatLng(init_street,function(point) {//set center point in map
if (point){
map.setCenter(point, zoom);
map.addOverlay(createMarker(point,init_street));
map.openInfoWindow(point,init_street);
}
});
}
map.addControl(new GLargeMapControl());
map.setMapType(G_NORMAL_MAP);
}
}`
function(data, responseCode) {
if(responseCode == 200) {
var texts = [];
var addresses = [];
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("item");
alert (markers.length);
for (var i = 0; i < markers.length; i++) {
var address=markers[i].getElementsByTagName('address').item(0).childNodes.item(0).nodeValue;
if (address!=null){
//alert (address);
var title=markers[i].getElementsByTagName('title').item(0).childNodes.item(0).nodeValue;
var link=markers[i].getElementsByTagName('link').item(0).childNodes.item(0).nodeValue;
var desc=markers[i].getElementsByTagName('description').item(0).childNodes.item(0).nodeValue;
desc=desc.substr(0,220);//limit
addresses.push(address);
texts.push("<div style='width: 200px'><a target='_blank' href='" +link+"'>"+title+"</a><br />"+desc+"</div>");
}//if
}//for
for (var i = 0; i < addresses.length; i++) {
geocoder.getLatLng(addresses[i], function (current) {
return function(point) {
if (point) map.addOverlay(createMarker(point,texts[current]));
}
}(i));
}
}//if });
I Understand the issue of needing a callback function to load the markers, but Im lost..
Any help apreciated!! ;)
Thx in advanced!!
This usually happens when fetching data with Ajax or similar. Basically when you fetch the data you need to utilize a callback function to wait for the data. If you don't there is no data to execute on. However, if you pause the execution with a alert() the data will have been fetched in the background.
Think of it as the waiting for the DOM to load before executing Javascript on the page.
I can't give you a better answer as you have not included the code that is calling the function you included.