Problems hiding google maps marker onClick event - javascript

I have put some markers for specific locations in a map, and I have two buttons, one to hide all the markers (clearOverlays) and other to show them again (showOverlays) but it isn't working. In my JavaScript console I am getting this error : Cannot call method 'setMap' of undefined
Here's my code..
// COORDENADAS
var coordenadas = [
['Punto 1', 19.558061,-99.296344, 4],
['Punto 2', 19.55886, -99.296886, 5],
['Punto 3',19.559103, -99.296688, 3],
['Punto 4', 19.560164,-99.297347, 2],
['Punto 5',19.560073,-99.296064, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng( 19.561883, -99.298287),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var ventana = new google.maps.InfoWindow();
var marcador, i;
for (i = 0; i < coordenadas.length; i++) {
marcador = new google.maps.Marker
({
position: new google.maps.LatLng(coordenadas[i][1], coordenadas[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(
marcador, 'mouseover', (function(marcador, i) {
return function() {
ventana.setContent(coordenadas[i][0]);
ventana.open(map, marcador);
}
})(marcador, i)
);
}
function clearOverlays(map) {
for (var i = 0; i < coordenadas.length; i++) {
marcador[i].setMap(null);
}
setAllMap(null);
console.log('click Ocultar');
}
function showOverlays(map) {
for (var i = 0; i < coordenadas.length; i++) {
marcador[i].setMap(map);
}
setAllMap(map);
console.log('click Mostar');
}

marcador is not an array. marcador[i] doesn't exist. That gives the error message: Cannot call method 'setMap' of undefined
You need an array of google.maps.Marker objects.
var gmarkers = [];
function clearOverlays(map) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
function showOverlays(map) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
for (i = 0; i < coordenadas.length; i++) {
var marcador = new google.maps.Marker
({
position: new google.maps.LatLng(coordenadas[i][1], coordenadas[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
gmarkers.push(marcador);
google.maps.event.addListener(
marcador, 'mouseover', (function(marcador, i) {
return function() {
ventana.setContent(coordenadas[i][0]);
ventana.open(map, marcador);
}
})(marcador, i)
);
}
working example

Related

google heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined

I'm working on a project where I have a JSON that looks like this
[
{
"lat": 53.1522756706757,
"lon": -0.487157731632087,
"size": 63,
"field": "TestField",
"variety": "TestVariety",
"count": 1
}
]
Which will have others with locations and count values.
I keep getting the above-titled error when using the following code.
let map;
let testField = new google.maps.LatLng(53.150, -0.488);
let options = {
zoom: 6,
center: testField,
mapTypeId: 'satellite',
};
function createMap(data) {
let mapElement = document.getElementById('map');
let geometry, weighted, count, heatData;
let heatmap, points;
map = new google.maps.Map(mapElement, options);
heatData = [];
for (var i = 0; i < data.length; i++) {
geometry = data[i];
weighted = {};
count = data[i].count;
weighted.location = new google.maps.LatLng(
data.lat,
data.lon);
weighted.weight = count
heatData.push(weighted);
}
points = new google.maps.MVCArray(heatData);
console.log(data);
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
opacity: 0.9,
radius: 20
});
heatmap.setMap(map);
}
$(function () {
$.ajax({
type: "GET",
url: "field_example.json",
dataType: "json",
success: createMap
});
});
There is something I'm not quite grasping here and help will be very much appreciated.
You get the error message: TypeError: Cannot read property 'NaN' of undefined because data.lat & data.lon are undefined. Changing data.lat to geometry.lat and data.lon to `geometry.lon (or using data[i] instead of data) fixes that.
for (var i = 0; i < data.length; i++) {
var weighted = {};
count = data[i].count;
weighted.location = new google.maps.LatLng(
data[i].lat,
data[i].lon);
weighted.weight = count
heatData.push(weighted);
}
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatData
});
proof of concept fiddle
code snippet:
// This example requires the Visualization library. Include the libraries=visualization
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization">
var map, heatmap;
function initMap() {
let map;
let testField = new google.maps.LatLng(53.150, -0.488);
let options = {
zoom: 6,
center: testField,
mapTypeId: 'satellite',
};
var data = [{
"lat": 53.1522756706757,
"lon": -0.487157731632087,
"size": 63,
"field": "TestField",
"variety": "TestVariety",
"count": 1
}]
function createMap(data) {
let mapElement = document.getElementById('map');
let count, heatData;
let heatmap, points;
map = new google.maps.Map(mapElement, options);
heatData = [];
console.log(data.length);
for (var i = 0; i < data.length; i++) {
var weighted = {};
count = data[i].count;
weighted.location = new google.maps.LatLng(
data[i].lat,
data[i].lon);
weighted.weight = count
heatData.push(weighted);
}
points = heatData;
console.log(points);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatData
});
heatmap.setMap(map);
}
createMap(data);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3.41&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=visualization&callback=initMap">
</script>

Google maps api filter checkbox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>

HTTP Request inside a function not works

I have this controller for AngularJS Framework.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var locations =[]; var map; var markers = [];
$scope.mappa = function(){
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.507033, lng: 15.080257},
zoom: 8
});
}
$scope.insert = function(){
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data)
{locations = data;});
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true);
}
};
In html file, i have a button that calls the insert function.
But if I run this code, the button works at the second time only. Instead if the http request is out of the function, the button works immediatly. Why?
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data)
{locations = data;});
$scope.insert = function(){
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true); }
};
It's asynchronous method. Move the code insert into callback success.
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) {
var marker, i;
for (i = 0; i < data.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i][0], data[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true); }
}
});
But if I run this code, the button works at the second time only.
It works at the first time, it's just AJAX request is asynchronous, so the location variable is not populated yet by the time your are trying to use it. When you click next time, it turns out that data has already loaded and location is set and "cached".
You need to do your stuff in callback function:
$scope.insert = function () {
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati").success(function (data) {
var marker, i, locations = data;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i < markers.length; i++) {
markers[i].setVisible(true);
}
});
};
And finally, when you make it work, consider moving your request logic into reusable service, making requests in controller is not the best design:
$scope.insert = function () {
locations.get().then(function(data) {
var marker, i, locations = data;
// ...
});
};

Google map not getting centered

The google map i am using does not get centered about the mean point i have calculated.
The code for the initialization is given. The map appears to be zoomed out a lot and its center far off from the center i have calculated. The mean appears in the extreme top left of the map. What is the problem here?
I am displaying the map in Bootstrap modal.
function initializeMap()
{
var xMean = 0.0;
var yMean = 0.0;
for(var i=0;i<points.length;i++)
{
xMean += parseFloat(points[i][0]);
yMean += parseFloat(points[i][1]);
}
xMean /= parseFloat(points.length);
yMean /= parseFloat(points.length);
var myMean = new google.maps.LatLng(xMean, yMean);
var mapOptions = {
zoom:17,
center:myMean
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i<points.length;i++) {
path.push(new google.maps.LatLng(points[i][0],points[i][1]));
bounds.extend(path[i]);
};
map.fitBounds(bounds);
//Displaying the markers
var marker;
for (var i = 0; i < path.length; i++) {
marker = new google.maps.Marker({
position: path[i],
map: map
});
}
//Displaying the path
for (var i = 0; i<path.length-1; i++) {
var start = path[i];
var end = path[i+1];
requestDirections(start,end);
}
}
by using:
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
you seem to overwrite myMean coordinates

Rectangular Overlays appearing only after dragging the map

I have a lot of markers and I m using markerClusterer to display them on the map.Additionally on click of a checkbox I need to display a rectangular overlay (title) near all these markers.
I have written 2 functions as follows for creating the overlay and deleting it.
function createLabel(posi,name){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = name;
var label = new Label({
position:posi,
map: map,
text:name
});
rectangleNombre[posicion]=label;
rectangleNombre[posicion].setMap(map);
console.log("add: etiquetaNombre",etiquetaNombre);
myfun();
}
function deletelabel(name){
for(var i = 0; i < etiquetaNombre.length; i++){
if(etiquetaNombre[i] == name){
rectangleNombre[i].setMap(null);
rectangleNombre.splice(i, 1);
etiquetaNombre.splice(i, 1);
}
}
console.log("delete marker"+name);
console.log("delete: etiquetaNombre",etiquetaNombre);
myfun();
}
I m invoking the createLabel function as follows:
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
var latLng = new google.maps.LatLng(40, -100);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(40, -100),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < 10; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var div=document.createElement('div');
var marker = new google.maps.Marker({
position: latLng,
draggable: false,
map: map,
title:"marker"+i
});
posi=marker.position;
name=marker.title;
createLabel(latLng,name);
markers.push(marker);
}
markerClusterer = new MarkerClusterer(map, markers);
Since I am using markerClusterer I had to customize it for my above requirement.I had done it as below.
Cluster.prototype.addMarker = function(marker) {
/// some lines
if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
// Min cluster size not reached so show the marker.
marker.setMap(this.map_);
posi=marker.position;
name=marker.title;
createLabel(posi,name);
}
if (len == this.minClusterSize_) {
// Hide the markers that were showing.
for (var i = 0; i < len; i++) {
this.markers_[i].setMap(null);
name=this.markers_[i].title;
deletelabel(name);
}
}
if (len >= this.minClusterSize_) {
marker.setMap(null);
name=marker.title;
deletelabel(name);
}
this.updateIcon();
return true;
};
The myfun() is called on click of check box is as below.
function myfun(){
var element=document.getElementById('id1');
if(element.checked){
for(var i = 0; i < etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
console.log("in my fun element checked",etiquetaNombre);
}
google.maps.event.addListener(map, 'bounds_changed', function () {
if(element.checked){
for(var i=0; i<etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
}
});
}
The problem which I m facing here is that on zooming when the clustered markers are disintegrated the rectangular overlays do not appear for them.But on simply dragging the map it appears.Can anybody guide what I m doing wrong here.
[Edited]
function createLabel(xCenter , yCenter, nombre,banderaPersonalizada){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = nombre;
var RectangleBounds = new google.maps.LatLngBounds(new google.maps.LatLng(yCenter,xCenter), new google.maps.LatLng((yCenter+1),(xCenter+1)));
rectangleNombre[posicion] = new RectangleNombre(RectangleBounds);
rectangleNombre[posicion].setMap(map);
}
function RectangleNombre(bounds, opt_weight, opt_color) {
this.bounds_ = bounds;
this.weight_ = opt_weight || 2;
this.color_ = opt_color || "#888888";
}
RectangleNombre.prototype = new google.maps.OverlayView();
RectangleNombre.prototype.onAdd = function(map) {
var idDiv = "normal-"+etiquetaNombre[posicion];
var div = document.createElement("div");
div.id = idDiv;
div.innerHTML = '<span style=" color:blue; font-family:arial; font-size:7.5pt; font-weight:900" > '+etiquetaNombre[posicion]+'</span>';
div.style.position = "absolute";
console.log("banderaCheckEtiqueta"+banderaCheckEtiqueta);
if(banderaCheckEtiqueta){
div.style.display = "";
} else {
div.style.display = "none";
}
this.getPanes().mapPane.appendChild(div);
this.map_ = map;
this.div_ = div;
}
RectangleNombre.prototype.draw = function() {
var proj = this.getProjection();
var c1 = proj.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var c2 = proj.fromLatLngToDivPixel(this.bounds_.getNorthEast());
this.div_.style.width = "0px";
this.div_.style.height = "0px";
this.div_.style.left = c1.x - 12;
this.div_.style.top = c1.y + 2;
}

Categories

Resources