How to solve map.addlayer not a function - javascript

I am trying to implement the leaflet-panel-layer plugin and customize the included overlay to my needs. The original code uses a geojson formatted as js and I use a basic js marker list (which I load in from a seperate document) so I am wondering what I have to change to show the markers. I already got some parts of the map working e.g. choosing between baselayers but I can´t get the overlaylayers to work how I want.
I think the loading in isn´t the problem here, its just that I cant add the markers to the map, because the follwing Error seems to have to do something with how and where the map is definined (info from other people with similar error message)
``leaflet.js:5 Uncaught TypeError: map.addLayer is not a function
at NewClass.addTo (leaflet.js:5:64472)
at URD_Regio.js:105:284``
How I load in the js files with the Markers in them:
<script src="js/URD_Regio.js"></script>
<script src="js/URD_Fernverkehr.js"></script>
How I define my markers (in the mentioned external js file) and how I group them:
var ulm_1 = L.marker([44.7892, 9.745775]);
ulm_1.bindPopup('<b>.....');
var db_regio = L.layerGroup ([ulm_1],......).addTo(map)
I have tried adding the addTo(map) command in several places but pretty much always got the same error.
My current code:
var overLayers = [
{
group: "data",
collapsed: true,
layers: [
{
active: false,
name: "Drinking Water",
layer: L.layerGroup(db_regio) //.addTo(map)?
},
Note when implementing the original code which uses a geojson formatted as js, the code works just fine.
How I define my map:
var map = L.map('map', { zoom: 6, center: L.latLng([52.3900214, 12.419982]) }), osmLayer = new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

Related

Microsoft.Maps.SDKMap is undefined, when creating object in BingMaps V8

While creating bingmap instance, SDKMap is undefined. Is there any missing credentials in following code?
function GetBingMap(){
var vcredentials = "<%=this.credentialKey%>" //credential Key
var vzoomLevel = Number("<%=this.zoom%>"); //Zoom Level
// Create the Map instance
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), //div map load
{
credentials: vcredentials, //credential
zoom: vzoomLevel, //zoom level
showZoomButtons: false, // enable Zoom Buttons
showLocateMeButton: false, // show Locate me button
showMapTypeSelector: false,//enable Map type selector
showScalebar: false,//enable scale bar
showTermsLink: false//enable terms link
});
this.map= map;
Make sure that the Bing Maps source code has loaded before calling your GetBingMap function. It sounds like it hasn't fully loaded before your code tries to create a map instance. If you are using async/defer in the script reference in the script tag, remove it.

How to add markers to leaflet map with tabletop.js?

I'm using this quite nice guide to add markers from a Google sheet to a basic leaflet.js map:
https://rdrn.me/leaflet-maps-google-sheets/
The problem is, using these code snippets here i get all the data logged and returned in the console, but none of the points appear on the map itself.
This is probably some really basic JavaScript issue that i'm not able to see. Sorry, still learning.
Here's a jfiddle, linking to a demo sheets with one marker point
https://jsfiddle.net/xfs19cz7/1/
with the map part:
function init() {
Tabletop.init({
key: '*url to gsheets here*',
callback: myFunction,
simpleSheet: true
})
}
window.addEventListener('DOMContentLoaded', init)
function myFunction(data, tabletop) {
console.log(data);
}
var map = L.map('map-div').setView([64.6220498,25.5689638], 5);
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Basemap (c) OpenStreetMap',
minZoom: 5,
maxZoom: 18
});
basemap.addTo(map);
function addPoints(data, tabletop) {
for (var row in data) {
var marker = L.marker([
data[row].Latitude,
data[row].Longitude
]).addTo(map);
marker.bindPopup('<strong>' + data[row].Info + '</strong>');
}
}
This should add one point to a basic map. Now actually the map is not at all rendered, and no marker shows up. I can't find any issues in the code making the map show up blank, but there probably are some.
The marker from gsheets is however logged in the console, i suspect there is something missing in my code relating to really basic javascript functions / looping / sloppy syntax.
Also tried the init() and addPoints(data, tabletop) parts to a map i had where the map with the same basemap link, which rendereded OK. Adding this still left the map rendering, but no markers showed up. Again, the gsheets was loaded as an array of objects.
Could anyone point me to this, probably very basic, issue in the code?
edit:
callback: myFunction,
line above needs to be changed to
callback: addPoints,
also, init function needs to be called and position set to absolute. Thanks for the working fiddle in answer marked as correct below.
Fixes
Try setting map position absolute
calling the init() function
Working fiddle

What would make a Google map Ag object returned without mapDataProvider?

I'm working on an SPA project (ionic, so it's angular with ui-router) where I need to display two different maps on two different pages/controllers.
The first map is a general map (let's call it the main map)where a few locations are marked and the second one (let's call it the edit map)is a focus on a specific location where the user can edit the location by dragging the marker.
The general implementation scheme I'm using is that I'm calling a initMap method from mappingService that instanciates a google map from each controller.
$rootScope.markers = [];
this.initMap = function initMap(mapTarget, mapCenter) {
// the initMap function initialize the map it takes two arguments:
// + mapTaget which defines the html element the map is bound to.
// + mapCenter that defines the center of the map and whether to display the center
var markup = "<div id='" + mapTarget.mapId + "'></div>";
document.getElementById(mapTarget.containerId).innerHTML = markup;
var centerPos = new google.maps.LatLng(mapCenter.lat, mapCenter.lng);
$rootScope.map = new google.maps.Map(document.getElementById(mapTarget.mapId), {
center: centerPos,
zoom: 18,
disableDefaultUI: true
});
// eventually place a person marker for the user's position
if (mapCenter.display) {
console.log('placing the position marker');
$rootScope.markers[0] = new google.maps.Marker({
position: {lat: mapCenter.lat, lng: mapCenter.lng},
map: $rootScope.map,
title: 'userLocation',
icon: './img/person_icon.png'
});
}
};
The only difference is that on the main map I'm first calling a geolocate service the return a promise and I'm using the returned location coordinates to then call the mapping service:
geolocateService.getLocalPosition()
.then(function(coords) {
mappingService.initMap(
{containerId: $scope.mapContainer, mapId: $scope.mapId},
{lat: coords.lat, lng: coords.lng, display: true}
);
While on the edit map I'm calling directly the mapping service.
mappingService.initMap(
{containerId: $scope.mapContainer, mapId: $scope.mapId},
{lat: $scope.location.lat, lng: $scope.location.lng, display: false}
);
I am able to render both maps without problem and even to add markers and some event listeners.
However, I run into the problem that after some sequence of actions, for example going from the main map to the edit map two times, one of the map would suddenly become blank (white to be exactly, so it doesn't seems to be something that I could solve by resizing the map). I'm receiving the Ag object and the only difference is that I don't get the mapDataProviders property on the broken map.
When it works, I get:
Ag object when it works
While when it doesn't, I get:
Ag object when it doesn't work
The code snippet above is my last implementation attempt. I've been trying to implement those maps from a lot of different ways to no avail. Among those attempts, I tried:
totally separates both instanciation, dividing the initMap methods into an initMainMap and an initEditMap.
using one instance for both maps and replacing the DOM element> This is what you see above with the following additional method that is called when leaving the view:
this.removeMap = function removeMap(containerId) {
var container = document.getElementById(containerId);
$rootScope.markers = [];
container.innerHTML = '';
// important part:
var old_element = container;
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
delete $rootScope.map;
}
knowing that on both views I have either:
or
<div id="edit-map-container"></div>
I'm trying to understand what would make the google map API return a map without mapDataProvider (which I believe means that the map works and even starts to render except that it lacks the tiles to display).
P.S. it looks like there is a memory leak, which is apparently a well known issue.
If anyone has the answer to this, I'm a bit lost right here!

Initializing two leaflet maps - one rewrites another

I'm trying to put multiple leaflet maps on one page, but I have problem with two of them - the second one rewrites the first one, so first one is rendering map, and the second has just grey area.
Here is the code:
var map_a = new L.Map( "smallMap", {
fullscreenControl: false,
layers: [osmMap]
}).setView([51.005, -0.09], 14);
var map_b = new L.Map( "smallMapSecond", {
fullscreenControl: false,
layers: [osmMap]
}).setView([51.505, -0.09], 14);
I have appropriate divs called smallMap and smallMapSecond. When I Initialize only one map, it works. Where could be the problem?
Well,one of the potential problems I see here without having a jsFiddle available is that you are using the same tileLayer osmMap for both maps. Sharing TileLayers between map instances is going to cause problems. Initialize tileLayers one per map.

Google maps block on contact page is giving offsetwidth error and messing up other modules in drupal 7

I have a working website running Drupal 7 with a few standard modules installed like views, panels and colorbox. Everything was working fine and I started creating a custom module with google maps to show a location on a map with a custom marker.
The map is working as intended and I didn't notice anything wrong until I went into my views admin. Somehow the JS code from the Gmap is messing up the config area of some of my modules. (Pop ups not working properly, buttons misplaced etc.)
EDIT:
When I enable this module the console displays "Uncaught TypeError: Cannot read property 'offsetWidth' of null" in main.js from google maps api I think.
Here is the code from the .js file:
(function ($) {
"use strict";
Drupal.behaviors.simple_gmap = {
attach: function (context) {
function initialize() {
// Map options.
var location = new google.maps.LatLng(51.5550390, 5.0843100);
var mapOptions = {
zoom: 17,
panControl: false,
zoomControl: true,
scaleControl: false,
qw2mapTypeControl: false,
rotateControl : false,
overviewMapControl : false,
scrollwheel : true,
center: location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
// Build the map and marker.
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var image = 'sites/all/modules/simple_gmap/images/icomaps.png';
var marker = new google.maps.Marker({
map: map,
position: location,
icon: image,
animation: google.maps.Animation.DROP,
title: 'Testtitle'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
};
})(jQuery);
I went over the code, but honestly i'm not sure what to look for. Thanks in advance for any help!
EDIT:
When I enable this module the console displays "Uncaught TypeError: Cannot read property 'offsetWidth' of null" in main.js from google maps api I think.
EDIT:
After some hours searching the best answer I found was that the map div is not being rendered before the javascript runs that needs to access it. I also read that (function ($) {} and drupal.behaviors in the js code are supposed to wait for the page to load. So I don't understand why it would give me that error.
Try reordering the JS files.
It might be that a js file is loaded before an other file is loaded that is needed.
For example, jQuery beeing loaded after jQuery functions are called.
I managed to get it working with some help at the Drupal forum! Gonna try to explain it here so it might help others figuring out this problem.
I was using a custom .module file that included the .js file I posted up top.
Code from my .module file:
function simple_gmap_init() {
drupal_add_js(drupal_get_path('module', 'simple_gmap') . '/simple_gmap.js');
drupal_add_js('http://maps.googleapis.com/maps/api/js?sensor=false', 'external');
}
function simple_gmap_block_info() {
$blocks['simple_gmap'] = array(
'info' => t('Google Map'),
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
function simple_gmap_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'simple_gmap':
$block['content'] = '';
}
return $block;
}
My .module file created a div with id "map_canvas" wherever I placed my block. I added this block to my contact page, which added the div ONLY on that page, but the .js file was being included in the head of every page. This caused the error "Uncaught TypeError: Cannot read property 'offsetWidth' of null" on every page but my contact page. Which broke my javascript in other modules.
This error was caused by my modules .js file looking for the "map_canvas" div, which was not present on any of the other pages.
What I did to solve the problem was include my .js file ONLY on the contact page where the "map_canvas" div existed.
I added the code written below at the bottom of the .module file:
<?php
function simple_gmap_form_alter(&$form, &$form_state, $form_id)
{
if($form_id == 'contact_site_form')
{
$form['map'] = array
(
'#markup' => '<div id="map_canvas"></div>',
'#weight' => -20, // adjust as necessary
'#attached' => array
(
'js' => array
(
array
(
'type' => 'file',
'data' => drupal_get_path('module', 'simple_gmap') . '/js/some_file.js',
),
),
)
);
}
}
?>
and I removed the code written below from the function simple_gmap_init():
drupal_add_js(drupal_get_path('module', 'simple_gmap') . '/simple_gmap.js');
This made sure the .js was only loaded on my contact page and not on any other page.
Also make sure you give the "map_canvas" a width and height in the css so it displays.
I've seen a LOT of posts last 2 days about this problem while searching for an answer and I hope this can help someone out. Good luck.

Categories

Resources