JQuery, Google Maps : "Cannot call methods on gmap prior to initialization" - javascript

I have a problem I've been trying to figure out for a while now.
There's a block of code that works fine, but then if I add some JQuery in it, it crash everything.
I get the following error : "Uncaught cannot call methods on gmap prior to initialization; attempted to call method 'addMarker"
The faulty code starts from "$.each(markersList.markers,"
Any help to point me out in the right direction would be greatly appreciated. Thanks !
function initialize() {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.each(markersList.markers,
function(map, marker) {
var destination = (marker.lat + ', ' + marker.lng);
$('#map_canvas').gmap('addMarker',
{ 'position': new google.maps.LatLng(marker.lat, marker.lng), 'title': marker.title }, function(map, marker) {
$('#map_canvas').gmap('addInfoWindow',
{ 'content': null }, function(iw) {
$(marker).click(function() {iw.open(map, marker);
map.panTo(marker.getPosition());
$('#to').val(destination);
alert("You've selected " + marker.title + " as your destination. Please enter the origin");
});
});
});
});
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
contentString = "Your location was found and has been added to starting point.";
map.setCenter(initialLocation);
$('#from').val(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});

I had a similar issue with mine, what I did was create the initialize function as a separate function from the rest of the code, when the page loads I call Initialize() and at the end of the function I call searchLocations() which adds all of the markers to the map.

Related

Google map is not loaded when open Browser

I have integrate a Google map in my website but map is not load in my website.But when I open inspect element map will work when I close inspect element map will disappear automatically.I don't know why its going like this,Please let me know what the problem. Here is my map code
Thanks in Advance
<div id="mapCanvas" style="width:100%; height:400px"></div>
<input type="text" title="Latitude" id="latt_val">
<input type="text" title="Longitude" id="long_val">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
document.getElementById("latt_val").value = latLng.lat();
document.getElementById("long_val").value = latLng.lng();
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(15.486432009100538, 73.82759375);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
google.maps.event.trigger(window,'resize',{});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
[UPDATE]
Hey, I'm still really curious what's going on here. Do you happen to have an AdBlocker enabled on your browser that might prevent the map from loading? Have you checked if this works in multiple browsers?
I made a codepen of our problem: http://codepen.io/trevorwhealy/pen/obRQdW.
And your map is working perfectly fine. If, on-load of this pen, you still do not see something, then I think we can safely say this is a browser issue.
[OLD POST]
Try putting your code:
google.maps.event.trigger(window,'resize',{}); // or trigger(map
after
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
but still within your initialize function.

Update marker in Leaflet

I have a problem with a marker in leaflet. My code is this:
var updateMarker = function(lat, lng) {
if($('.leaflet-marker-icon').length)
marker.setLatLng([lat, lng]);
else
var marker = L.marker([lat, lng]).addTo(map);
return false;
};
var updateMarkerByInputs = function() {
return updateMarker( $('#latInput').val() , $('#lngInput').val());
}
$('#latInput').on('input', updateMarkerByInputs);
$('#lngInput').on('input', updateMarkerByInputs);
map.on('click', function(e) {
$('#latInput').val(e.latlng.lat);
$('#lngInput').val(e.latlng.lng);
updateMarker(e.latlng.lat, e.latlng.lng);
});
As you can see, on the first click will be add a marker and in the next clicks it should be updated. But I get this error at the second click:
TypeError: i is undefined
..."_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:funct...
leaflet.js (line 6, col 603)
What do I wrong?
You are defining your marker variable locally in the updateMarker function, so the reference is lost as soon as the function returns.
Define it outside the function:
var marker;
var updateMarker = function(lat, lng) {
if($('.leaflet-marker-icon').length)
marker.setLatLng([lat, lng]);
else
marker = L.marker([lat, lng]).addTo(map);
return false;
};
This way you don't need to check the DOM with jQuery to find out if your marker is defined, you can check directly the marker variable:
var marker;
var updateMarker = function(lat, lng) {
if (marker) {
marker.setLatLng([lat, lng]);
} else {
marker = L.marker([lat, lng]).addTo(map);
}
return false;
};
(to improve readability I would suggest to always use brackets in your if statements.)

AJAX call in an Infowindow: Scope Issue

Or at least I believe it's a scope issue, correct me if I'm wrong.
I have a for loop that generates markers on my map. Each infowindow loads different content using callbacks to an ajax function.
I've simplified this sample to outline the problem.
var xhr = "";
var infowindow = new google.maps.InfoWindow();
var marker, i;
var polylineCoordinates = [new google.maps.LatLng(78.782762, 17.917843),
new google.maps.LatLng(-0.829439, -91.112473),
new google.maps.LatLng(15.066156, -23.621399),
]
function createHttpRequest() {
try {
xhr = new XMLHttpRequest();
return xhr;
}
catch (e)
{
//assume IE6
try {
xhr = new activeXBbject("microsoft.XMLHTTP");
return xhr;
}
catch (e) {
return alert("Unable to create an XMLHttpRequest object");
}
}
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(78.782762,17.917843),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
//I recreated the polylineCoordinates array (see above)
//to try and replicate and real array in the script
for (i = 0; i < polylineCoordinates.length; i++) {
marker = new google.maps.Marker({
position: polylineCoordinates[i],
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent("<div id=\"infowindow\">" + getStationInfo(infoWindowDiv) + "</div>");
infowindow.open(map, marker);
}
})(marker, i));
} //End adding markers loop
function infoWindowDiv(stationInfo) {
var add = document.createTextNode(stationInfo);
document.getElementById("infowindow").appendChild(add);
}
function getStationInfo(callback) {
//createHttpRequest() exists globally
var xhr = createHttpRequest();
var url = "stations.php" //edited out the original URL
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var stationInfo = "This is a Test";
return callback(stationInfo)
} //end readyState
} //end readystatechange
xhr.open("GET", url, true);
xhr.send(null);
} //end getStationInfo
Small Edit: Moved functions outside of the loop
Edit 2: There is nothing wrong with the ajax call, the url was edited for the sake of the sample code. Notice the final output shows "This is a test" in the infowindow which clearly states a successful callback was performed. Moreover, notice there is no responseText or responseXml. The variable being sent back has nothing to do with the url
The callback works fine but for some reason it's topped with the dreadful 'undefined' on top of it.
Console shows nothing.
Output:
undefined
This is a test
What am I doing wrong? How can it be undefined if it works?
What is happening:
you click on the infowindow
getStationInfo(infoWindowDiv) is called, fires off an AJAX request, but returns nothing useful ("undefined", there is no return statement)
The AJAX function will encounter an error (url "Unnecessary at this point" will not cause the onreadystatechange function to fire). But you tell us that isn't a problem.
The script encounters the javascript error Uncaught TypeError: Cannot call method 'appendChild' of null because the div with id infowindow hasn't been attached to the DOM.
Suggest adding an event listener on the infowindow to not attempt to access the div with id="infowindow" until it has been rendered (domready).
Working code:
var xhr = "";
var infowindow = new google.maps.InfoWindow();
var map = null;
var marker, i;
var polylineCoordinates = [new google.maps.LatLng(78.782762, 17.917843),
new google.maps.LatLng(-0.829439, -91.112473),
new google.maps.LatLng(15.066156, -23.621399)
]
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(78.782762,17.917843),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
for (i = 0; i < polylineCoordinates.length; i++) {
marker = new google.maps.Marker({
position: polylineCoordinates[i],
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent("<div id=\"infowindow\" style=\"height:50px;width:200px;\"></div>");
infowindow.open(map, marker);
google.maps.event.addListenerOnce(infowindow,"domready", function(){
getStationInfo(infoWindowDiv);
});
})(marker, i));
} //End adding markers loop
}
function infoWindowDiv(stationInfo) {
var add = document.createTextNode(stationInfo);
document.getElementById("infowindow").appendChild(add);
}
function getStationInfo(callback) {
var stationInfo = "This is a Test";
callback(stationInfo)
} //end getStationInfo
google.maps.event.addDomListener(window, 'load', initialize);

Duplicate a google map to a separate <div> element on page

I have one istance of a google map on a page. I'm using the following line of code to get the map and assign it to a new variable.
newmap = map.getMap();
When I print newmap to console it shows that the map is being assigned to the variable. I now want to duplicate that map with the exact same options into the following div....
<div id="map-larger-canvas"></div>
Any idea's how I would do this?
Define option for every map and after init twice:
var map_options = {
center: new google.maps.LatLng(41.811729,12.738513),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
function initialize() {
var map1 = document.getElementById('map-1st');
var map_canvas = document.getElementById('map-larger-canvas');
var map1 = new google.maps.Map(map1, map_options)
var map2 = new google.maps.Map(map_canvas, map_options);
}
google.maps.event.addDomListener(window, 'load', initialize);
I use Json in this way, take a look:
$('#map_canvas_europe').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'json/locations_europe.json', function(data) {
$.each( data.markers, function(i, marker) {
$('#map_canvas_europe').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map_canvas_europe').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
$('#map_canvas_asia').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'json/locations_asia.json', function(data) {
$.each( data.markers, function(i, marker) {
$('#map_canvas_asia').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map_canvas_asia').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});

Google Maps global object; js generated by coffeescript not working

What is the global object in a Google Maps app?
I rewrote the js at https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
in coffeescript, which generated the following javascript:
// Generated by CoffeeScript 1.6.3
(function() {
var errorFlag, initialize;
google.maps.visualRefresh = true;
initialize = function() {
var map, mapOptions;
mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(function(position) {
var infowindow, pos;
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found'
});
return map.setCenter(pos);
}, function() {
return handleNoGeolocation(true);
});
} else {
return handleNoGeolocation(false);
}
};
handleNoGeolocation(errorFlag = function() {
var content, infowindow, options;
if (errorFlag) {
content = 'Geolocation failed';
} else {
content = 'Your browser does not support Geolocation';
}
options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
infowindow = new google.maps.InfoWindow(options);
return map.setCenter(options.position);
});
google.maps.event.addDomListener(window, 'load', initialize);
}).call(this);
The app works when I use the js from their website, but not when I use the js generated by coffeescript. My guess is that since the map variable is a global variable in their code, I should bind it to the global object as well. I tried window.map, but that didn't work either. Any ideas?
The handleNoGeolocation function defination is wrongly compiled. It should have been
var errorFlag, initialize, handleNoGeolocation;
//..
//..
handleNoGeolocation = function (errorFlag) {
//..
//..
};
rather than
handleNoGeolocation(errorFlag = function() {
//..
//..
});
I guess something went wrong with indentation.
hope this helps.

Categories

Resources