Generate google map error - javascript

I have the following script which supposed to generate a basic google map:
$(document).ready(function(){
var weatherAPP = {
generateMap: function(){
console.log('called');
var mapHolder = document.getElementById('#map');
var mapOptions = {
center: new google.maps.LatLng(51.5072, 0.1275),
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapHolder, mapOptions);
}
};
weatherAPP.generateMap();
});
console.log('called') gets called fine.
I have included the following scripts in order:
google maps api
jquery
script
However I am getting the following error:
Uncaught TypeError: Cannot read property 'offsetWidth' of null

Since your element is: <section id="map"></section>
var mapHolder = document.getElementById('#map');
should be
var mapHolder = document.getElementById('map');
You must have confused it with jQuery or CSS in where you declare ids with the prefix #.
In document.getElementById you have to put the elements ID as it is with no prefix at all

I is happening because you have # in getElementById('#map');
If you remove the # it will work :)
http://jsfiddle.net/zbyqoaju/1/
var weatherAPP = {
generateMap: function () {
console.log('called');
var mapHolder = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng(51.5072, 0.1275),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapHolder, mapOptions);
}
};
weatherAPP.generateMap();

Related

Loading google map binding too soon

I tried using this code here: fiddle
But it keeps sending me a javascript error "Uncaught TypeError: Cannot read property 'x' of undefined".
I mostly think it because the element didn't have time to load before the init function was executed.
that's my view:
<div id="mapDiv" data-bind="map:myMap"></div>
that's my binding:
ko.bindingHandlers.map = {
init: function (element, valueAccessor, allBindingsAccessor) {
var mapObj = ko.utils.unwrapObservable(valueAccessor());
var latLng = new google.maps.LatLng(
ko.utils.unwrapObservable(mapObj.lat),
ko.utils.unwrapObservable(mapObj.lng));
var mapOptions = { center: latLng,
zoom: 15};
mapObj.googleMap = new google.maps.Map(element, mapOptions);
mapObj.marker = new google.maps.Marker({
map: mapObj.googleMap,
position: latLng,
title: "You Are Here",
});
$("#" + element.id).data("mapObj",mapObj);
}
};
and that's my viewmodel:
module.activate = function(settings){
var self = this;
this.myMap = ko.observable({
lat: 34.1,
lng: 31.6});
this.compositionComplete = function(child, parent, settings){
};
};
return module;
});
I made a fiddle with your code, and once I styled the map div to have height and width, it ran without a problem.
<div id="mapDiv" style="width:300px; height:300px" data-bind="map:myMap"></div>
I never did see any reference to x, so I can't say I've addressed your issue, but if you think you have something running before Google Maps is ready, see this solution for adding a listener for the idle event.

Load Script and Execute only if needed

I need to find if there are any divs with class="map" in a page Code Pen Example.
If there are, and only in that case, load Google Maps API.
Then use it to load the maps into the divs using data attributes for lat and long values.
So I have the following:
<div class="map" data-long="51.5072" data-lat="0.1275">
Replace by map 1
</div>
<div class="map" data-long="74.0059" data-lat="40.7127">
Replace by map 2
</div>
I was considering using something like (this should be loaded only if map divs exist):
$.getScript('https://www.google.com/jsapi', function()
{
google.load('maps', '3', { other_params: 'sensor=false', callback: function()
{
}});
});
The code I would like to apply to each map is something like Google Maps Code:
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Thank You,
Miguel
See a solution for loading Google Maps API async:
https://stackoverflow.com/a/12602845/1491212
var gMapsLoaded = false;
window.gMapsCallback = function(){
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
if(gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
Then just do something like this :
$(document).ready(function(){
function initialize(){
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
$(window).bind('gMapsLoaded', initialize);
if($('.map').length){
window.loadGoogleMaps();
}
});

Is any method to loading kml in background in html with java script

I trying to loading kml file on map in html but it takes more time to loading kml file on mobile screen
and then show kml file on map after long time.I want to know is any method to load it in background like android I used below code to loading kml file.
var geoXml = null;
var map = null;
var myLatLng = null;
var i;
jQuery(document).ready(function () {
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
var myOptions = {
zoom: 18,
center: new google.maps.LatLng(37.422104808, -122.0838851),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), myOptions);
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true
});
geoXml.parse('mykml.KML');
});

Unable to add marker in Google Maps Api v3

Since yesterday I'm trying to add marker in Google Maps Api v3 . I read the documentation and all. Here's my code :
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(28.63, 77.21),
zoom: 8,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
// google.maps.event.addDomListener(window, 'load', initialize);
function getFillingDetails(){
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
var lat = [];
var lon = [];
var price = [];
$.each(data, function(key, value){
lat.push(value.latitude);
lon.push(value.longitude);
price.push(value.price);
});
});
var myLatlng = new google.maps.LatLng(23.72,77.10);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map,
});
}
</script>
Everything looks fine to me. The initialize() function is called after onload of body tag.
And getFillingDetails() function is called when I click a button.
But still I'm getting no success.
You have a syntax error at:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map, <--- get rid of this comma
});
next time you should look in the developer console for any errors.
// To add the marker to the map, call setMap();
marker.setMap(map);
source : https://developers.google.com/maps/documentation/javascript/markers

How to embed google map?

I am trying to add a Google Map to my website, and I tried this:
$.getScript("https://maps.googleapis.com/maps/api/js?sensor=false", function () {
alert("1");
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
alert("2");
map = new google.maps.Map(document.getElementById("container"), myOptions);
});
This is not working. Can anybody tell me why?
EDIT
Script loaded perfectly. I know this because alert(1) shows but after that control does not reach alert(2).
document.getElementById(id)
What is id, where did that get defined?
Also getScript is for doing Ajax requests, which isn't really how you should be doing Google Maps. Just call the script in the normal way, and have an init function which executes on document ready. Or even better use the window.load event listener that the Google Maps API provides for you anyway.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" />
<script type="text/javascript">
function init(id)
{
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(id), myOptions);
}
google.maps.event.addDomListener(window, 'load', init('yourDivID'));
</script>
You have to use async loading for this - https://developers.google.com/maps/documentation/javascript/tutorial#asynch
In the current approach, the script do this-
function getScript(src) {
document.write('<' + 'script src="' + src + '"' + ' type="text/javascript"><' + '/script>');
}
So, when you call $.getScript, that will goto void. And, google.maps.LatLng becomes undefined.
I've created a version with the async one. You can check the fiddle # http://jsfiddle.net/rifat/G3yPw/
You should have a look on your container div.
It must have specified width and height.
And I used to separate the affectation of LatLng :
var map;
var ll = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: ll,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("container"), myOptions);

Categories