JavaScript callback function not recognising namespace properties or functions - javascript

I'm new to JavaScript and was really getting along well with it until a few hours ago and this has got me stumped.
My question is with the callback which i don't think i'm doing right. Essentially, on the Init of the App.Map which is called from the html page, the script will load the google maps script and execute the code in the callback. This all works fine. The problem is when i'm stepping through the script in the load function, the location should be null but isn't. However, if i use App.Map.location in place of location the variable is correct and equal to null.
Secondly, the commented out line ClearMarkers(); throws an error that it is not recognised when i step through the script.
I'm not doing something right, what would be the correct way to implement a callback this way?
Namespaces:
var App = App || {};
App.Map = App.Map || {};
App namespace:
(function(ns) {
ns.LoadScript = function(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState === 'loaded' ||
script.readyState === 'complete') {
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = function() {
callback();
}
}
script.src = url;
document.head.appendChild(script);
};
})(App);
Map namespace:
(function(ns) {
ns.position = {
lat: -34.397,
lng: 150.644
};
ns.location = null;
var key = '';
var map;
var markers = [];
ns.ClearMarkers = function () {
if (markers.length !== 0) {
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
}
};
var load = function () {
map = new google.maps.Map(document.getElementById('map'), {
center: this.position
});
//ClearMarkers();
if (location) {
alert("perform search with this location");
} else {
alert("find current location");
}
};
ns.Init = function (data, options) {
this.location = data && data.location ? data.location : null;
App.LoadScript('https://maps.googleapis.com/maps/api/js?key=' + key + '&libraries=places', load);
};
})(App.Map);
Thanks for any help and if the question needs reworking please let me know.

Related

javascript DOM object (window) extended property is null on page reload after being idle

I have a custom extended property attached to the window object in JavaScript as follows:
Community.js
(function (window, document, $) {
'use strict';
var containerScrollPositionOnHideList = [];
var scrollToTopOnShowContainerList = [];
var userProfileInfo = {};
window.Community = $.extend({
//init
init: function () {
var Site = window.Site;
Site.run();
this.enableHideShowEventTrigger();
},
setUserInfo: function (userObj) {
if (UtilModule.allowDebug) { debugger; }
window.localStorage.setItem('userInfo', JSON.stringify(userObj));
var d = new $.Deferred();
$.when(this.initUserProfile(userObj.UserId)).done(function () {
d.resolve("ok");
});
},
getUserInfo: function () {
var userJson = window.localStorage.getItem('userInfo');
var userObj = JSON.parse(userJson);
return userObj;
},
})(window, document, jQuery);
The problem is that this extension property window.Community is null in certian scenarios when i refresh the page which i am going to describe below along with flow of code.
and here is a module in JavaScript to force reload scripts even if they are cached every time the page is refreshed as my code heavily depends on javascript calls so I just enabled it to make sure while I am still writing the code page reloads every time, the code is below as follows:
Util.js
var UtilModule = (function () {
var allowDebug = false;
var currentVersion = 0;
var properlyLoadScript = function (scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function () {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript(scriptPath)).done(function () {
callBackAfterLoadScript();
d.resolve("ok");
});
}
else {
console.log('Community loaded already and running now : ' + scriptPath);
callBackAfterLoadScript();
}
return d.promise();
};
var forceReloadScript = function (scriptPath) {
if (UtilModule.allowDebug) { debugger; }
var d = $.Deferred();
initCurrentVersion();
var JSLink = scriptPath + "?version=" + currentVersion;
var JSElement = document.createElement('script');
JSElement.src = JSLink;
JSElement.onload = customCallBack;
document.getElementsByTagName('head')[0].appendChild(JSElement);
function customCallBack() {
d.resolve("ok");
}
return d.promise();
};
var enableDebugger = function () {
allowDebug = true;
};
var disableDebugger = function () {
allowDebug = false;
};
var debugBreakPoint = function () {
if (allowDebug) {
}
};
var initCurrentVersion = function () {
if (currentVersion == 0) {
var dt = new Date();
var ttime = dt.getTime();
currentVersion = ttime;
}
};
var getCurrentVersion = function () {
return currentVersion;
};
return {
forceReloadScript,
properlyLoadScript,
enableDebugger,
disableDebugger,
debugBreakPoint,
allowDebug,
getCurrentVersion
};
})();
Note: I have made deferred objects to resolve only when the JSElement.onload has been called successfully. This step was taken just for testing purpose to make sure that I am not missing something before reaching a point to call the method where I am getting an error.
After that the code where I load scripts using UtilModule in my layout file look like as below:
_Layout.cshtml
<script src = "~/Scripts/Application/Modules/Util.js" ></script>
<script>
$.when(
UtilModule.properlyLoadScript('/Scripts/Application/Community.js', () => {
// Community.init() was supposed to be called here but i was still getting the error so i implemented this using promise that is returned from properlyLoadScript and call Community.init() further in .done callback to make sure that script is properly loading till this point.
//window.Community.init();
})
).done(function() {
window.Community.init();
});
</script>
#RenderSection("scripts", required: false)
Now coming to my main file where My index file is executing having (_layout.chsmtl) as parent layout
is
Index.cshtml
#{
ViewBag.Title = "My Blog";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<article id="BlogPage" style="margin: 5px;">
</article>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$.when(UtilModule.properlyLoadScript('/Scripts/Application/Modules/Blog.js', () => {
})).done(function () {
BlogModule.init();
});
});
//});
</script>
}
from what I know is that #section scripts is executed only once all the scripts in the layout page are loaded first so seems like a safe place to initialize the code which is dependent on some script in _Layout.HTML file and further enclosed with $(document).ready() for testing just to make sure that this script loads after everything else is loaded already.
Note: I am running all this code in in-cognito mode in chrome so nothing is cached while this code is running
now my Blog.js file looks like as below
var BlogModule = (function () {
var moduleReference = this;
var PageId = "#BlogPage ";
var currentUser;
var BlogPostList = [];
var blogPostInfo = {};
//init
var init = function () {
if (UtilModule.allowDebug) { debugger; }
//This is where the problem happens
console.log(window.Community);
console.log(window.Community.getUserInfo());
currentUser = window.Community.getUserInfo();
initBlogInformation();
//window.Community.registerModule(BlogModule);
if (Object.keys(window.Community.getUserProfileObject()) <= 0) {
$.when(window.Community.initUserProfile(currentUser.UserId)).then(function () {
$.when(initBlogInformation()).done(function () {
//debugger;
console.log(BlogPostList);
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
});
}
else {
$.when(initBlogInformation()).done(function () {
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
}
};
var loadBlogIndexMenuWidget = function () {
if (UtilModule.allowDebug) { debugger; }
};
var loadBlogPostWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogPostWidget";
widgetOptions.container = PageId + "#BlogPostWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
}
var loadBlogViewWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogViewWidget";
widgetOptions.container = PageId + "#BlogViewWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var loadBlogCommentsWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogCommentsWidget";
widgetOptions.container = PageId + "#BlogCommentsWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var initBlogList = function () {
$.when(getBlogPosts()).then(function (results) {
if (UtilModule.allowDebug) { debugger; }
BlogPostList = results.Record;
console.log(BlogPostList);
});
};
var getBlogPosts = function () {
if (UtilModule.allowDebug) { debugger; }
var d = new $.Deferred();
var uri = '/Blog/GetBlogPosts?userId=' + currentUser.UserId;
$.post(uri).done(function (returnData) {
if (UtilModule.allowDebug) { debugger; }
if (returnData.Status == "OK") {
BlogPostList = returnData.Record;
BlogPostList.map(x => {
if (UtilModule.allowDebug) { debugger; }
x.UserName = window.Community.getUserProfileObject().UserName;
if (x.Comments != null) {
x.CommentsObject = JSON.parse(x.Comments);
x.CommentsCount = x.CommentsObject.length;
}
});
console.log(returnData.Record);
d.resolve("ok");
} else {
window.Community.showNotification("Error", returnData.Record, "error");
d.resolve("error");
}
});
return d.promise();
};
var initBlogInformation = function () {
//debugger;
var d = $.Deferred();
getBlogPosts().then(getBlogModelTemplate()).then(function () {
d.resolve("ok");
});
return d.promise();
};
//Get Blog Model
var getBlogModelTemplate = function () {
var d = new $.Deferred();
var uri = '/Blog/GetBlogModel';
$.post(uri).done(function (returnData) {
blogPostInfo = returnData.Record;
d.resolve("ok");
});
return d.promise();
};
return {
init: init,
};
})();
The error I have highlighted below
so the problem is in init function of BlogModule which is BlogModule.init() the page is idle for too long and I reload it I get the following error:
cannot call
window.Community.getUserInfo() of undefined implying that community is undefied
after couple of refreshes its fine and the issue doesn't happen unless I change reasonable portion of code for js files to be recompiled again by browser or the browser is idle for too long and I am not able to understand what is triggering this issue.
below is log from console
p.s. error occurs more repeatedly if i refresh page with f5 but happens rarely if i refresh page with ctrl + f5
Please any help would be of great value
Answering my own question, took a while to figure it out but it was a small mistake on my end just fixing the following function in Util.js fixed it for me
var properlyLoadScript = function(scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function() {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript('/Scripts/Application/Community.js')).done(function() {
//debugger;
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
d.resolve("ok");
});
} else {
console.log('Community loaded already and running now : ' + scriptPath);
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
}
return d.promise();
};

zopim callback is never called

Following the instruction of the this documentation, I end up with the following code:
window.zEmbed || (function (d, s) {
var z = $zopim = function (c) { z._.push(c) },
$ = z.s =
d.createElement(s), e = d.getElementsByTagName(s)[0]; z.set = function (o) {
z.set.
_.push(o)
}; z._ = []; z.set._ = []; $.async = !0; $.setAttribute("charset", "utf-8");
$.onload = (event) => {
console.log("chat script has loaded");
};
$.src = "//v2.zopim.com/?#zopimClientID"; z.t = +new Date; $.
type = "text/javascript"; e.parentNode.insertBefore($, e);
})(document, "script");
var onChatStart = function () {
$zopim.livechat.window.show();
window['onChatStart'] && window['onChatStart']();
};
$zopim(function () {
$zopim.livechat.clearAll();
(......)
});
The problem is that the $zopim(funtion() {..}) callback function is never called, but the script is successfully loaded. I know based on the console.log made by:
$.onload = (event) => {
console.log("chat script has loaded");
};
Any one knows why this is happening?
Thank you
The problem is you're running the $zopim script before it's fully loaded. Once all the parts of the $zopim object have loaded it will stop looping and run your script.
var zopimConfig = function() {
$zopim(function() {
$zopim.livechat.clearAll();
(......)
});
};
var waitForZopim = setInterval(function () {
if (
window.$zopim === undefined ||
window.$zopim.livechat === undefined ||
window.$zopim.livechat.departments === undefined
) {
return;
}
zopimConfig();
clearInterval(waitForZopim);
}, 100);
Waiting for window.$zopim.livechat.departments is optional, however if you're doing anything around departments I would recommend keeping this

Angularjs: Google Map Api - Google is not defined

I'm working on an angularjs single-page application, and I'm trying to build a mapping system for the application. The map is loading fine, however whenever I attempt to use the geocode functionality, I get the error referenceError: Google is not defined.
Map controller
(function () {
'use strict';
angular
.module('CityWits')
.controller('mapCtrl', mapCtrl);
mapCtrl.$inject = ['$scope', '$http', 'mapApi', '$q'];
function mapCtrl($scope, $http, mapApi, $q){
var vm = this;
vm.setQuery = setQuery;
// todo: Switch this out with deals that are loaded depending on the radius of the map
getBranches();
function setQuery(query) {
console.log("business deal filter controller : query=" + query);
vm.query = query;
vm.focus = false;
}
function getBranches(){
$http.get('app/cwitsTestData/branchData.json').then(function(data){
vm.branches = sortBranches(data.data.branches);
$scope.$broadcast("branchesSorted", vm.branches);
});
}
}
function sortBranches(branches){
var locations, address, text;
locations = [];
for(var branch in branches){
address = branches[branch].address;
text = address.street_line1 + " " + address.city+ " " +address.state;
locations.push(text);
}
return locations;
}
})();
Here's the google factory I wrote to handle the api:
(function() {
'use strict';
angular
.module('CityWits')
.factory('mapApi', mapApi);
function mapApi () {
var mapApi = {}
var markers = [];
var geocoder;
var service;
mapApi.geocode = geocode;
mapApi.marker = marker;
mapApi.distance = distance;
return mapApi;
function geocode (addresses){
geocoder = new google.maps.Geocoder();
var coords = [];
if(geocoder){
for(var i in addresses){
geocoder.geocode( { 'address': addresses[i]}, function(results, status) {
if (status === 'OK') {
coords.push(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
}
function distance(start, end, method="DRIVING"){
service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: start,
destinations: end,
travelMode: method
}, function (status, response){
if(status ==! "OK"){
console.log("Error: "+status);
} else {
console.log("distance measured");
var result = {};
for(var i in response.rows){
result = response.rows[i].element;
}
return result;
}
});
}
function marker(positions, json){
if(markers.length > 0){
for(o in markers){
markers[o].setMap(null);
}
}
for(x in positions){
}
}
}
})();
And lastly this is the directive that initiates the api:
(function () {
'use strict';
angular
.module('CityWits')
.directive('dealMap', dealMap);
dealMap.$inject = ['$timeout', '$http', 'mapApi'];
function dealMap($timeout, $http, mapApi){
var directive = {
link: link,
templateUrl: 'app/map/map.directive.html',
scope: {
deals: '=',
branches: '='
},
restrict: 'EA'
};
return directive;
function link(scope, element, attrs) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB4RaOArTNm9C7crfutMVc0KkWIoQG-ZE0";
document.body.appendChild(script);
$timeout(function(){
scope.initialize();
}, 500);
// todo: Do stuff after deals are loaded based on map radius
scope.$on('branchesSorted', function(event, data) {
console.log('deals loaded');
console.log(data);
var points = mapApi.geocode(data);
console.log(points);
});
scope.initialize = function() {
scope.mapOptions = {
zoom: 8,
center: new google.maps.LatLng(22.649907498685803, 88.36255413913727)
};
scope.map = new google.maps.Map(document.getElementById('map'), scope.mapOptions);
};
console.log(scope);
}
}
})();
Apparently this error occurs since the Google Maps API is not yet loaded.
The moment when the data is getting loaded:
$http.get('app/cwitsTestData/branchData.json').then(function(data){
vm.branches = sortBranches(data.data.branches);
$scope.$broadcast("branchesSorted", vm.branches);
});
and afterwards once Geocoder is utilized, there is no any guarantee that Google Maps API is already loaded at that moment:
scope.$on('branchesSorted', function(event, data) {
console.log('deals loaded');
console.log(data);
var points = mapApi.geocode(data); //<--Google Maps API could be still not loaded at that moment
console.log(points);
});
since Google Maps library is getting loaded asynchronously in your example like this:
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB4RaOArTNm9C7crfutMVc0KkWIoQG-ZE0";
document.body.appendChild(script);
I would propose the following solution instead.
Let's introduce the following service to load Google Maps API, create the map and notify once it is ready:
.factory('googleMapsApi', function ($rootScope,$window, $q) {
return {
load: function (key) {
var deferred = $q.defer()
if ($window.google && $window.google.maps) {
deferred.resolve($window.google);
}
else {
var url = 'https://maps.googleapis.com/maps/api/js?callback=googleMapsLoad';
if (key) url += "&key=" + key;
var script = document.createElement('script');
script.type = 'text/javascript'
script.src = url;
$window.googleMapsLoad = function () {
deferred.resolve($window.google);
}
document.body.appendChild(script);
}
return deferred.promise;
},
createMap : function(scope,id,options){
var mapObject = new google.maps.Map(document.getElementById(id), options);
scope.$emit('google-maps-loaded',mapObject);
},
onMapReady : function(scope, ready){
var handler = $rootScope.$on('google-maps-loaded', function(evnt,data){ return ready(data);});
scope.$on('$destroy', handler);
}
}
})
Then the map could be created like this via link function of directive:
link: function (scope, element, attributes) {
googleMapsApi.load(scope.key)
.then(function () {
var mapOptions = {
center: scope.center,
zoom: scope.zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
googleMapsApi.createMap(scope,attributes.id,mapOptions);
});
}
and data is loaded in controller like this:
.controller('MyCtrl', function ($scope, googleMapsApi) {
googleMapsApi.onMapReady($scope, function(mapInst) {
console.log('Google Map is ready');
mapInst.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
});
});
JSFiddle example

Google maps API returning null zip code (used to work)

I've been using the following code for a while now and noticed it has stopped working and throwing an error. The alert says null. Has the maps API changed? I've loaded up
https://maps.googleapis.com/maps/api/js?sensor=false
and
https://maps.gstatic.com/intl/en_us/mapfiles/api-3/15/5/main.js
function geo(){
if(navigator.geolocation) {
var fallback = setTimeout(function() { fail('10 seconds expired'); }, 10000);
navigator.geolocation.getCurrentPosition(
function (pos) {
clearTimeout(fallback);
console.log('pos', pos);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if(status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
alert(zip);
var homecity;
var homezip;
if((zip[1]>21201)&&(zip[1]<21298)) {
//document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
homecity = "Baltimore";
homezip = zip[1];
//$("._res").html(homecity+" "+homezip);
window.location.href = "?city="+homecity+"&zip="+homezip;
}
if((zip[1]>20001)&&(zip[1]<20886)) {
//document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
homecity = "D.C.";
homezip = zip[1];
//$("._res").html(homecity+" "+homezip);
window.location.href = "?city="+homecity+"&zip="+homezip;
}
if((zip[1]>19019)&&(zip[1]<19255)) {
//document.getElementById('geo').innerHTML = "Baltimore "+zip[1];
homecity = "Philadephia";
homezip = zip[1];
//$("._res").html(homecity+" "+homezip);
window.location.href = "?city="+homecity+"&zip="+homezip;
}
}
});
}, function(err) {
fail(err.message+" WTF");
}
);
}
Simple fix, just change the 0 in the res to 1:
var zip = res[1].formatted_address.match(/,\s\w{2}\s(\d{5})/);

Google Maps API issue with IE8

I'm writing some code with the Google Maps API, it works fine in all browsers (FF, IE9, Chrome) but IE8 or below, I have assigned the map to a global variable called Map, which gets populated but when the addMarker function gets called the Map global is null in IE8, but the addMarker function does work when I call it from the locator function, I have included all these functions below.
var GoogleMaps = {};
var Map = null;
var init = (function () {
"use strict";
var MapType = null;
var ZoomLevel = null;
var ControlPos = null;
var ControlSize = null;
var myLatLong = null;
var Geocoder;
var result = null;
GoogleMaps.setup = function (options) {
myLatLong = new google.maps.LatLng(24.886436490787712, -70.26855468754);
if (google.loader.ClientLocation) {
myLatLong = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude);
} else if (options.Lat !== null && options.Long !== null) {
options.Location = new google.maps.LatLng(options.Lat, options.Long);
} else {
// Else centre to UK
options.Location = new google.maps.LatLng(52.961875, -1.419433);
}
if (options.MapType.toUpperCase() === 'ROADMAP') {
MapType = google.maps.MapTypeId.ROADMAP;
} else if (options.MapType.toUpperCase() === 'TERRAIN') {
MapType = google.maps.MapTypeId.TERRAIN;
} else if (options.MapType.toUpperCase() === 'HYBRID') {
MapType = google.maps.MapTypeId.HYBRID;
} else {
MapType = google.maps.MapTypeId.SATELLITE;
}
// Check zoom level, if not set then set to zoom level 8.
if (options.ZoomLevel) {
ZoomLevel = options.ZoomLevel;
} else {
ZoomLevel = 8;
}
var mapOptions = {
center: myLatLong,
zoom: ZoomLevel,
mapTypeId: MapType
};
var mapDiv = document.getElementById('canvas');
// Map gets initiated here
window.Map = new google.maps.Map(mapDiv, mapOptions);
delete options.MapType;
delete options.Lat;
delete options.Long;
delete options.ZoomLevel;
};
GoogleMaps.addMarker = function (options) {
var Location = null;
var Animation = null;
var Title = null;
var Draggable = null;
var Content = null;
var InfoWindow = null;
var Flat = null;
var Clickable = null;
if (options.lat !== null && options.long !== null) {
Location = new google.maps.LatLng(options.lat, options.long);
;
} else {
Location = myLatLong;
}
if (typeof(options.position) !== "undefined") {
Location = options.position;
}
if (options.animation.toUpperCase() === 'BOUNCE') {
Animation = google.maps.Animation.BOUNCE;
} else if (options.animation.toUpperCase() === 'DROP') {
Animation = google.maps.Animation.DROP;
} else {
Animation = google.maps.Animation.NONE;
}
if (options.draggable !== null && options.draggable === 'true') {
Draggable = true;
} else {
Draggable = false;
}
if (options.title !== null) {
Title = options.title;
} else {
Title = null;
}
if (options.content !== null) {
Content = options.content;
InfoWindow = new google.maps.InfoWindow({
content: Content
});
}
if (options.flat !== null && options.flat === 'true') {
Flat = true;
} else {
Flat = false;
}
if (options.clickable !== null && options.clickable === 'true') {
Clickable = true;
} else {
Clickable = false;
}
// Gets used in this section
var Marker = new google.maps.Marker({
position: Location,
map: window.Map,
animation: Animation,
draggable: Draggable,
title: Title,
flat: Flat,
clickable: Clickable,
zIndex: 1
});
// and sets map here
Marker.setMap(window.Map);
if (options.content !== null) {
google.maps.event.addListener(Marker, 'click', function (e) {
InfoWindow.open(window.Map, this);
google.maps.event.addListener(window.Map, 'click', function (e) {
InfoWindow.close(window.Map, window.Marker);
});
});
}
google.maps.event.addListener(Marker, 'dragend', function (e) {
});
delete options.lat;
delete options.long;
delete options.animation;
delete options.title;
delete options.content;
delete options.flat;
delete options.draggable;
delete options.clickable;
};
GoogleMaps.Locator = function (result) {
var address = null;
Geocoder = new google.maps.Geocoder();
address = result;
Geocoder.geocode({ 'address': address }, function (response, status) {
if (status === google.maps.GeocoderStatus.OK) {
window.Map.setCenter(response[0].geometry.location);
var Location = new google.maps.LatLng(response[0].geometry.location.Xa, response[0].geometry.location.Ya);
var markerOptions = {
animation: "drop",
draggable: "true",
content: 'Hello World!',
title: "Hello",
position: Location
};
GoogleMaps.addMarker(markerOptions);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
Below is how I am calling the functions:
var markerOptions = {
lat: 52.48278,
long: -0.892089,
animation: "drop",
draggable: "true",
content: 'Hello World!',
title: "Click Me"
};
google.maps.event.addDomListener(window, 'load', function () { GoogleMaps.setMarker(markerOptions) });
google.maps.event.addDomListener(window, 'load', function () { GoogleMaps.Locator('London') });
Thanks for any help.
I resolved the problem like this.
<meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE7; IE=EmulateIE9″/>
Try changing this line in your setup
window.Map = new google.maps.Map(mapDiv, mapOptions);
to just
Map = new google.maps.Map(mapDiv, mapOptions);
This way you accessing the global variable declared.
when is GoogleMaps.setup called? Right now it looks like depending on the browser it can be called after functions attached by
google.maps.event.addDomListener(window, 'load', function () { ... });
and that's why map is not set when you call addMarker, but is already initialized when you receive callback from
Geocoder.geocode(...)
To fix this make sure that GoogleMaps.setup is called before addMarker.
IE8 has always meant trouble. :-) Try adding the following meta tag at the beginning of your <head> section:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
Description here:
http://blogs.msdn.com/b/ie/archive/2008/06/10/introducing-ie-emulateie7.aspx

Categories