Uncaught ReferenceError: mapInitialised is not defined - javascript

$(document).ready(function(){
// Initialise global variables
var geoJson = getMarkers();
var homeLatitude = 50.351;
var homeLongitude = -3.576;
var initialZoom = 15;
var mapInitialised = 0;
// Initialise map
var map = mapInit();
function mapInit() {
// initialise map
if ( mapInitialised===0 ) {
var map = L.mapbox.map('map', 'mapIdentifier.234grs')
.setView([homeLatitude, homeLongitude], initialZoom);
mapInitialised = 1;
}
return map;
}
});
I get the error Uncaught ReferenceError: mapInitialised is not defined inside the 'mapInit' function.
I'm still learning here and am unsure of what I'm doing wrong.
Edit: here's the whole code that I'm using in this app:
$(document).ready(function(){
// Initialise global variables
var geoJson = getMarkers();
var homeLatitude = 50.351;
var homeLongitude = -3.576;
var initialZoom = 15;
var mapInitialised = 0;
// Initialise map
var map = mapInit();
// Add features to map
var myLayer;
addFeaturesToMap(map, myLayer);
// Define map behaviour
myLayer.on('click', function(e) {
e.layer.openPopup();
});
// define button behaviour for switching between map and list
$('#buttonMap').click(function(){
switchToMap();
});
// define button behaviour for switching between map and list
$('#buttonList').click(function(){
switchFromMap();
});
$('.view-on-map').click(function(e){
// Scroll to the top of the map
$(document).scrollTo(0,500);
// get lat, long, and name for event location
var latitude = $(this).attr("data-latitude");
var longitude = $(this).attr("data-longitude");
var name = $(this).attr("data-name");
// go to map
switchToMap();
// show popup
var popup = L.popup()
.setLatLng([latitude, longitude])
.setContent('<p><strong>' + name + '</strong></p>' )
.openOn(map);
}); // end of view-on-map click function
}); // end of document ready function
function getMarkers() {
// define geoJson object
var geoJson = {
type: 'FeatureCollection',
features: []
};
var arrayLength = events.length;
// loop through events array and push into geoJson object
for (var i = 0; i < arrayLength; i++) {
var latitude = events[i].location[0].latitude;
var longitude = events[i].location[0].longitude;
var name = events[i].location[0].name;
var pageId = events[i].location[0].pageId;
var link = events[i].location[0].link;
var description = events[i].location[0].description;
var feature = {
type: 'Feature',
properties: {
title: name,
other: "text",
'marker-color': '#54a743',
'stroke': '#428334',
url: link
},
geometry: {
type: 'Point',
coordinates: [longitude, latitude]
}
}
// push to geoJson.features array
geoJson.features.push(feature);
}
return geoJson;
}
function switchToMap() {
// show map
$('#map').fadeIn();
// change button states
$('#buttonMap').attr("disabled", "disabled");
$('#buttonList').removeAttr("disabled");
}
function switchFromMap() {
// hide map
$('#map').fadeOut();
// change button states
$('#buttonList').attr("disabled", "disabled");
$('#buttonMap').removeAttr("disabled");
}
function mapInit() {
// initialise map
if ( mapInitialised===0 ) {
var map = L.mapbox.map('map', 'mapIdentifier.234grs')
.setView([homeLatitude, homeLongitude], initialZoom);
mapInitialised = 1;
}
return map;
}
function addFeaturesToMap(map, myLayer) {
// declare feature layer
myLayer = L.mapbox.featureLayer().addTo(map);
// Pass features and a custom factory function to the map
myLayer.setGeoJSON(geoJson);
// set template for popup
myLayer.eachLayer(function(layer) {
var content = 'Location:' + layer.feature.properties.title;
layer.bindPopup(content);
});
}

Isn't "mapInitialised" only in the scope of the function in which it is declared? I think once you fix the scoping of that variable, you will then run into similar issues with other variables used in "mapInit()", like "homeLatitude".

Related

is there a way to prevent Here maps from removing all the polyline & objects instead of just removing the marker and showing the new ones

The problem is like this.
When the user clicks on a traceroute link in our app it opens a popup with here maps, showing the polyline with multiple markers in it. And on the same popup there is another table that has a map icon, when clicked shows only one marker in the here maps. The problem is both the multiple markers and single marker are showing properly initially(first time) but when i press the map icon that just shows only one marker for the second marker to be shown the removeObjects get called and it removes all the polyline and the markers that was previously shown(good) but then it stops showing the new marker and the previously passed polyline in the map(hence the problem to come here). can anybody help me solve this challenge.
addMarkerToGroup(group, coordinate, html) {
this.marker1 = new H.map.Marker(coordinate);
// var marker = new H.map.Marker(coordinate);
// add custom data to the marker
this.marker1.setData(html);
group.addObject(this.marker1);
}
addInfoBubble(map,data1,ui) {
for (let i = 0; i < data1.length; i++ ) {
var group = new H.map.Group();
map.addObject(group);
// add 'tap' event listener, that opens info bubble, to the group
group.addEventListener('tap', function (evt) {
// event target is the marker itself, group is a parent event target
// for all objects that it contains
var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), {
// read custom data
content: evt.target.getData()
});
// show info bubble
ui.addBubble(bubble);
}, false);
this.addMarkerToGroup(group, {lat: data1[i].start_latitude, lng: data1[i].start_longitude},
'' +data1[i].stop_address+
'');
}
}
addInfoBubble1(map,data1,ui) {
var group = new H.map.Group();
map.addObject(group);
// add 'tap' event listener, that opens info bubble, to the group
group.addEventListener('tap', function (evt) {
// event target is the marker itself, group is a parent event target
// for all objects that it contains
var bubble = new H.ui.InfoBubble(evt.target.getGeometry(), {
// read custom data
content: evt.target.getData()
});
// show info bubble
ui.addBubble(bubble);
}, true);
this.addMarkerToGroup(group, {lat: data1.start_latitude, lng: data1.start_longitude},
'' +data1.stop_address+
'');
}
addMarkertopolyline(map, data) {
let objm = data;
for (let i = 0; i < objm.length; i++) {
this. Group = new H.map.Group();
map.addObject(this. Group);
if (i == 0) {
var coords = { lat: objm[0].latitude, lng: objm[0].longitude },
marker0 = new H.map.Marker(coords, {icon: new H.map.Icon('../../../../assets/images/truckstartb1.svg', {size: {w: 36, h: 36}})});
map.addObject(marker0);
map.setCenter(coords1);
this.group.addObject(marker0);
}
if (i == objm.length - 1) {
var coords1 = { lat: objm[objm.length - 1].latitude, lng: objm[objm.length - 1].longitude },
marker0 = new H.map.Marker(coords1, {icon: new H.map.Icon('../../../../assets/images/flagsb2.svg', {size: {w: 36, h: 36}})});
map.addObject(marker0);
map.setCenter(coords1);
this.group.addObject(marker0);
}
}
}
addMarker(map,data1) {
for (let i = 0; i < data1.length; i++) {
this.iconHMap = new H.map.Icon("../../../../../assets/images/cargogrey.svg", {size: {w: 36, h: 36}});
var icon = this.iconHMap;
this.group = new H.map.Group();
map.addObject(this. Group);
var cords = { lat: data1[i].start_latitude, lng: data1[i].start_longitude },
icon1 = {icon: this.iconHMap},
// coords = {lat: lat, lng: lng},
marker = new H.map.Marker( coords, {icon: this.iconHMap});
map.addObject(marker);
map.setCenter(coords);
this.group.addObject(marker);
}
}
addMarker1(map,data1) {
this.iconHMap = new H.map.Icon("../../../../../assets/images/cargogrey.svg", {size: {w: 36, h: 36}});
var icon = this.iconHMap;
this.group = new H.map.Group();
map.addObject(this. Group);
var cords = { lat: data1.start_latitude, lng: data1.start_longitude },
icon1 = {icon: this.iconHMap},
// coords = {lat: lat, lng: lng},
marker = new H.map.Marker(coords, { icon: this.iconHMap });
var coords = { lat: data1.start_latitude, lng: data1.start_longitude },
icon1 = { icon: this.iconHMap };
var marker = new H.map.Marker(coords, { icon: this.iconHMap });
map.addObject(marker);
map.setCenter(coords);
this.group.addObject(marker);
}
addPolylineToMap(map, data) {
var lineString = new H.geo.LineString([data[0].latitude, data[0].longitude, 0]);
// var growingPolygon = new H.geo.Polygon(lineString),
// growingShape = new H.map.Polygon(growingPolygon);
let objl = data;
let ob;
let obj;
for (let i = 0; i < objl.length; i++) {
this.polyline = { style: { lineWidth: 4 } };
lineString.pushLatLngAlt(objl[i].latitude, objl[i].longitude, 0);
map.addObject(new H.map.Polyline(lineString, this.polyline));
}
}
loadMap1(data, data1) {
const platform = new H.service.Platform({
apikey: 'q3j2RP34Zz5SdH2bFYIVQP1PbMGSSh4PH3OjLml0oaA'
});
const layers = platform.createDefaultLayers();
this.div = document.getElementById('hereMap'); // this.mapDiv.nativeElement
const map = new H.Map(this.div, layers.vector.normal.map, { pixelRatio: window.devicePixelRatio, center: { lat: this.lat1, lng: this.long1 }, zoom: 5, });
this.hereMap = map;
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.hereMap));
// Create the default UI components
var ui = H.ui.UI.createDefault(this.hereMap, layers);
// Window resize handler
window.addEventListener('resize', function () {
map.getViewPort().resize();
});
this.addPolylineToMap(this.hereMap, data);
this.addMarker(this.hereMap, data1);
this.addMarkertopolyline(this.hereMap, data);
this.addInfoBubble(this.hereMap, data1, ui);
}
removeObjects() {
if (this.traceroutelist1.length > 1) {
this.hereMap1.removeObjects(this.group.getObjects());
// this.group.removeObjects();
}
}
loadMap(data, data1) {
const platForm1 = new H.service.Platform({
apikey: 'q3j2RP34Zz5SdH2bFYIVQP1PbMGSSh4PH3OjLml0oaA'
});
const layers1 = platForm1.createDefaultLayers();
this.div1 = document.getElementById('hereMap1');
const map = new H.Map(this.div1,layers1.vector.normal.map,{ pixelRatio: window.devicePixelRatio,center: {lat: this.lat1, lng: this.long1},zoom: 5,});
this.hereMap1 = map;
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => this.hereMap1.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.hereMap1));
// Create the default UI components
this.ui = H.ui.UI.createDefault(this.hereMap1, layers1);
// Window resize handler
window.addEventListener('resize', function () {
map.getViewPort().resize();
});
this.addPolylineToMap(this.hereMap1, data);
this.addMarker1(this.hereMap1, data1);
this.addMarkertopolyline(this.hereMap1, data);
this.addInfoBubble1(this.hereMap1, data1, this.ui);
}
And here is the html part
<div [class.show]="isHereMap" [class.hide]="kmtrack" [class.none]="transfer">
<div #map id="hereMap"></div>
</div>
<div [class.show]="isHereMap" [class.hide]="kmtrack" [class.showpointer]="transfer">
<div #map id="hereMap1"></div>
</div>
And this is the function that calls the traceroute when the map icon is clicked
mapReady1(row) {
this.transfer = true;
this.isHereMap1 = true;
this.isHereMap = false;
this.kmtrack1 = true;
const d = new Date();
const fdate = this.datepipe.transform(d, 'yyyy-MM-dd');
const ftime = '12:00 am';
const ttime = this.datepipe.transform(d, 'hh:mm a');
this.startdatetime = fdate + ' ' + ftime;
this.enddatetime = fdate + ' ' + ttime;
const dt = new Date(this.enddatetime);
const d1 = dt.setDate(dt.getDate() - 1); // 24 hour format old code
var t = new Date();
t.setHours(0, 0, 0, 0); // 12 hour format new code
this.traceStart = this.datepipe.transform(t, 'yyyy-MM-dd hh:mm a');
const req1 = {
role: this.data.userdetails.rolename,
userId: this.data.userdetails.usersid,
user_id: this.data.userdetails.usersid,
company_id: this.data.rowdata.company_id,
start_date: this.traceStart + '/' + this.enddatetime,
vehicle_id: this.data.rowdata.vehicle_id,
};
this.tracerouteService.getTracerouteList(req1).subscribe((response) => {
this.responsedata = response;
this.kmtrack = false;
this.transfer = true;
this.isHereMap1 = true;
this.isHereMap = false;
if (this.responsedata.success === "true") {
this.icondest1 = this.icondest;
this.iconstart1 = this.iconstart;
this.kmtrack = false;
this.visible = true;
this.value = this.responsedata.data.totalValue;
this.trackVehicleResponse = this.responsedata.data.totalValue;
this.traceroutelist = this.responsedata.data.trace;
this.traceroutelist1.push(this.traceroutelist);
this.removeObjects();
this.loadMap(this.traceroutelist, row);
this.addPolylineToMap(this.hereMap1, this.traceroutelist);
this.addMarker1(this.hereMap1, row);
this.addMarkertopolyline(this.hereMap1, this.traceroutelist);
this.addInfoBubble1(this.hereMap1, row, this.ui);
this.obj = this.traceroutelist;
this.tlen = this.obj.length;
// console.table(this.obj);
this.lat2_1 = this.latSelected;
this.long2_1 = this.longSelected;
this.traceroutelist.forEach((latAndLong: any) => {
this.lat = parseFloat(latAndLong.start_latitude);
this.long = parseFloat(latAndLong.start_longitude);
return (this.latAndLong02 = Array(latAndLong));
// return this.long01, this.long02;
});
} else {
this.lat1 = 23.473324;
this.long1 = 77.947998;
this.zoom = 4;
this.boundcheck = false;
this.visible = false;
}
return this.latAndLong02;
// this is the end of the logic for polyline
});
// this.zoom0 = 6;
}
Not the perfect one but this will do i guess:
https://angular-ivy-bb3x8u.stackblitz.io
As, you can see in the example i'm not even able to produce the polyline with custom icons and info bubble on stackblitz in the main map id(hereMap). The problem arises when i click on the buttons with numbers (in my local code it's a map icon) where the removeobjects API call is removing all the polyline and the markers in the second hidden map(hereMap1) when clicked on any iterated button for the second time and that's why i have posted it here.(sorry need to learn to post with good coding standards)
Regarding https://stackblitz.com/ :
Regarding this documentation you need to Add a registry entry to the NPM configuration by executing the following command:
npm config set #here:registry https://repo.platform.here.com/artifactory/api/npm/maps-api-for-javascript/
and
npm install #here/maps-api-for-javascript --save
This is not possible on https://stackblitz.com/
Is not possible to implement .npmrc file too: https://github.com/stackblitz/core/issues/1851
Ok, regarding your code:
It seems you are using two maps in different map containers - this is correct. But this.group is using for both maps? - You need to create two group each to other map.
I see this.group is often overwritten in your code but it should be created (in most cases) once and then this.group.addObject, this.group.removeObject many times.
I see in your code this.group and this.Group. If you want create another group then please using another name, because is very difficult to read this code.

Nuxt js: Google maps markers wont show and loop is not working

I have a function that loops over an object to populate the markers. But when I do run the code, the loop is not working. Also when I do console.log, it is not showing me anything even in Vue DevTools. I am not using any Vue packages for the Google map. I just followed the documentation, and wrote the vanilla JavaScript functions.
Here is the whole function:
export default {
layout:'adminLte',
data(){
return{
address:{
lat:7.0650673,
lng:125.5961476
},
clinic:[],
markersInfo:[],
}
},
methods:{
loadScript() {
if (window.google && window.google.maps) {
this.initMap();
return;
}
var self = this;
var script = document.createElement("script");
script.onload = function() {
if (!window.google && !window.google.maps)
return void(console.error("no google maps script included"));
self.initMap();
};
script.async = true;
script.defer = true;
script.src = "https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=geometry";
document.getElementsByTagName("head")[0].appendChild(script);
},
initMap(){
var center = new google.maps.LatLng(this.address.lat, this.address.lng)
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: center
})
//this are for the markers. even if i console log below. it wont show anything
for (var i = 0; i < this.clinic.length; i++) {
var clinicLat = this.clinic.data[i].lat;
var clinicLng = this.clinic.data[i].lng;
var details = this.clinic.data[i].name;
var latLng = new google.maps.LatLng(clinicLat,clinicLng);
console.log(details)
var markers = new google.maps.Marker({
position: latLng,
map: map,
icon: {
url: "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
},
size: new google.maps.Size(20, 20),
});
const contentString = '<div id="content"><p>' + details + '</p></div>';
//for Info windows function
console.log('Markers' + markers)
this.infoWindowShow(markers, contentString);
this.markersInfo.push(markers)
}
},
infoWindowShow(markers, contentString) {
var infowindow = new google.maps.InfoWindow({
content: contentString
});
markers.addListener('click', function() {
infowindow.open(markers.get('map'), markers);
});
},
showMarker(id) {
google.maps.event.trigger(this.markersInfo[id], 'click');
},
getClinicsList(){
firebase.database().ref('clinics').on('value',(snapshot)=>{
this.clinic = snapshot.val()
console.log(snapshot.val())
this.loadScript()
})
},
},
created(){
console.log('created')
this.getClinicsList()
if (localStorage.getItem("user-email") === null) {
this.$router.push('/login')
}
},
mounted(){
this.loadScript()
}
}
The HTML element for map:
<div class="card-body table-responsive">
<div id="map" style="width: 1200px; height: 600px;"></div>
</div>
Still the DevTools is empty, but the clinic array has values.
JSFiddle
Before the map markers even get created, the for-loop hits a runtime error, caused by a couple issues in your code.
Issue 1: clinic is not an Array
As seen in the screenshot, clinic is actually set to an Object:
The for-loop assumed clinic was an Array, and iterated with a numeric index, but that won't work properly with your Object. One solution is to use Object.values() for iteration like this:
// BEFORE:
// for (var i = 0; i < this.clinic.length; i++) {
for (const item of Object.values(this.clinic)) {
Issue 2: item.data does not exist
Your loop is trying to access a nonexistent data prop in each clinic item (i.e., var clinicLat = this.clinic.data[i].lat), but the lat and lng props are actually at the root of the object, as seen in the screenshot:
So you could just access the props directly from the item reference. Using the corrected for-loop from above:
// BEFORE:
// for (var i = 0; i < this.clinic.length; i++) {
// var clinicLat = this.clinic.data[i].lat;
// var clinicLng = this.clinic.data[i].lng;
// //...
// }
for (const item of Object.values(this.clinic)) {
const clinicLat = item.lat
const clinicLng = item.lng
//...
}
Working JSFiddle with changes above

Markers keeps overlays on every move map

I am learning leaflet . My idea was to create map with clusters
, everything works but when I move map new markers keep
overlay old ones.I could see that every time i move map marker gets bolder, so i assume they overlay each other.
How to remove old ones ? I tried everything , cant figure out,
here is code:
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
var marker;
var clusters = {}; // key is lat/lon, value is a L.MarkerClusterGroup
var nodecounts = {};// key is lat/lon, value is the number of nodes at that location
var markers = {}; // key is plot id, value is an L.Marker
// Browsable map
function initMap(lat,lon,zoom){
// set up the AJAX stuff
ajaxRequest=GetXmlHttpObject();
if (ajaxRequest==null) { return; }
// set up the map
map = new L.Map('map');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 20, attribution: osmAttrib});
if (!lat) { lat=44.3008813; lon=-79.6114973; zoom=14; }
map.setView(new L.LatLng(lat,lon),zoom);
map.addLayer(osm);
askForPlots();
map.on('moveend', onMapMove);
}
function askForPlots() {
// request the marker info with AJAX for the current bounds
var bounds=map.getBounds();
var minll=bounds.getSouthWest();
var maxll=bounds.getNorthEast();
$("#regTitle").html("Hello World");
$("#listings").load('/engine/boxlistings.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat);
var msg='/engine/box.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat;
ajaxRequest.onreadystatechange = gotPlots;
ajaxRequest.open('GET', msg, true);
ajaxRequest.send(null);
}
function onMapMove(e) {
askForPlots();
}
function gotPlots() {
if (ajaxRequest.readyState!=4 || ajaxRequest.status!=200) return;
var resp = JSON.parse(ajaxRequest.responseText);//.replace(/[^\u000A\u0020-\u007E]/g, "")
var plotlist = resp.plots;
// First, tot up the number at each position, so we know whether to cluster
for (var i=0; i<plotlist.length; i++) {
var plot = plotlist[i];
if (markers[plot.id]) continue;
var ll = new L.LatLng(plot.lat,plot.lon, true);
var key= locationKey(ll);
nodecounts[key] = (nodecounts[key] || 0) + 1;
}
// Custom
var mapcluster = L.markerClusterGroup({ chunkedLoading: true,maxClusterRadius:60 });
for (var i = 0; i < plotlist.length; i++) {
var a = plotlist[i];
var title = a.name;
var marker = L.marker(L.latLng(a.lat, a.lon), {
icon: new L.DivIcon({
className: 'tooltips',
html: ''+
'<div class="triangle" id="'+a.id+'"><strong>'+a.price+'</strong></div>'
})
});
marker.bindPopup(title);
mapcluster.addLayer(marker);
}
map.addLayer(mapcluster);
console.log(mapcluster);
}
function locationKey(ll) { return ll.lat.toFixed(5)+","+ll.lng.toFixed(5); }
// Single plot map
// AJAX support
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); }
return null;
}
Any help appreciated
I use this function:
function removeMarkers() {
map.eachLayer(function (layer) {
layer.remove();
});
}
But it also removes the map so I follow with:
L.imageOverlay(imageUrl, imageBounds).addTo(map);

adding multiple AddListener in polygons google map

I have added on a google map some polygons and multipolygons from geojson data.
My need is to print out the name of the countries in an infowindow when the event "mousemove" is in the polygon. I have also set a legend and i want to reload it when the event "dblclick" is on the polygon.
Here's my problem: I can't do the "mousemove" and the "dblclick" event for all the polygons and multipolygons, it just take the last one polygon and multipolygon casted by my function.
Here's my full code (UPDATE):
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var countries = ['Germany','France','Moldova','Italy','Spain'];
var infoWindow = document.createElement('div');
infoWindow.id = 'infoWindow';
var content1 = [];
content1.push('<h3>Default </h3>');
infoWindow.innerHTML = content1.join('');
infoWindow.index = 2;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(infoWindow);
var state = new google.maps.Data();
var poly ;
var polys = new Array();
var gaArr = new Array();
var p = 0;
var mp = 0;
//the problem is here
state.addListener('addfeature',function(evt) {
//my 5 objects pass here
var CouName = evt.feature.getProperty('name');
if (evt.feature.getProperty('type') == 'Polygon') {
var ga = state.getFeatureById(CouName);
var gaGeom = ga.getGeometry();
gaArr = gaGeom.getAt(0).getArray();
poly = new google.maps.Polygon({paths:gaArr, map:map,clickable:false,visible:false});
google.maps.event.addListener(map,'dblclick',function(evt){
if (google.maps.geometry.poly.containsLocation(evt.latLng, poly)) {
legend.innerHTML = CouName;
}
});
google.maps.event.addListener(map,'mousemove',function(evt){
if (google.maps.geometry.poly.containsLocation(evt.latLng, poly)) {
infoWindow.innerHTML = CouName;
}
});
p++;
}
if (evt.feature.getProperty('type') == 'MultiPolygon') {
var ga = state.getFeatureById(CouName);
var gaGeom = ga.getGeometry();
gaArr = gaGeom.getArray();
for (var i=0;i<gaGeom.getArray().length;i++){
polys[i]= new google.maps.Polygon({paths:gaArr[i].getAt(0).getArray(), map:map,clickable:false,visible:false});
}
google.maps.event.addListener(map,'dblclick',function(evt){
for(var i=0;i<gaArr.length;i++){
if (google.maps.geometry.poly.containsLocation(evt.latLng, polys[i])) {
legend.innerHTML = CouName;
}
}
});
google.maps.event.addListener(map,'mousemove',function(evt){
for(var i=0;i<gaArr.length;i++){
if (google.maps.geometry.poly.containsLocation(evt.latLng, polys[i])) {
infoWindow.innerHTML = CouName;
}
}
});
mp++;
}
});
for (var country in countries){
state.loadGeoJson('http://.../GoogleMaps/'+countries[country]+'.geojson', {
idPropertyName: 'name'
});
}
state.setMap(map);
//to color the polygons
state.setStyle(function(feature) {
var k = feature.getProperty('color');
return {
fillOpacity:0.6,
fillColor:k,
strokeWeight:1,
clickable: false
}
});
I Think the problem is the Polygon array polys and the polygon poly are deleted when state.addListener pass to another polygon or multipolygon, and as i said, the addlistener works for the last ones polygon and multipolygon casted by the function.
I don't know if it can help but below is an example of my geojson files:
{"type":"Feature","properties":{"color":"purple","name":"Germany","type":
"MultiPolygon"},"geometry":{"type": "MultiPolygon","coordinates":
[[[[8.5636100769042969,54.684165954589844],
[8.5948600769042969,54.719856262207031],[8.5851364135742187,54.7445068359375],
[8.5511093139648437,54.753883361816406],[8.4447212219238281,54.74832...]]]]}}
{"type":"Feature","properties":{"name": "Moldova","color":"green","type":
"Polygon"},"geometry":{"type": "Polygon","coordinates":
[[[28.108325958251953,46.102291107177734],[28.0...]]]]}}
I thought about looping on all multipolygons and polygons and making an array of polygons and an array of array of polygons but it didn't work.
I found the answer. I update below state.addListener:
state.addListener('addfeature',function(evt) {
var CouName = evt.feature.getProperty('name');
if (evt.feature.getProperty('type') == 'Polygon') {
var c = p;
var ga = state.getFeatureById(CouName);
var gaGeom = ga.getGeometry();
gaArr = gaGeom.getAt(0).getArray();
//here I push all my polygons in my array poly
poly.push(new google.maps.Polygon({paths:gaArr, map:map,clickable:false,visible:false}));
google.maps.event.addListener(poly[c],'dblclick',function(evt){
alert(poly.length);
if (google.maps.geometry.poly.containsLocation(evt.latLng, poly[c])) {
legend.innerHTML = CouName;
}
});
google.maps.event.addListener(map,'mousemove',function(evt){
if (google.maps.geometry.poly.containsLocation(evt.latLng, poly[c])) {
infoWindow.innerHTML = CouName;
}
});
p++;
}
if (evt.feature.getProperty('type') == 'MultiPolygon') {
var cp= mp;
var ga = state.getFeatureById(CouName);
var gaGeom = ga.getGeometry();
gaArr = gaGeom.getArray();
for (var i=0;i<gaGeom.getArray().length;i++){
//here I push all my polygons of my multipolygons in my array polys
polys.push(new google.maps.Polygon({paths:gaArr[i].getAt(0).getArray(), map:map,clickable:false,visible:false}));
}
google.maps.event.addListener(map,'dblclick',function(evt){
for(var i=cp;i<cp+gaGeom.getArray().length;i++){
if (google.maps.geometry.poly.containsLocation(evt.latLng, polys[i])) {
legend.innerHTML = CouName;
}
}
});
google.maps.event.addListener(map,'mousemove',function(evt){
for (var i=cp;i<cp+gaGeom.getArray().length;i++){
if (google.maps.geometry.poly.containsLocation(evt.latLng, polys[i])) {
infoWindow.innerHTML = CouName;
}
}
});
mp=mp+gaGeom.getArray().length;
}
});

How to centralized the heat-map area in the map after zoom-in?

I'm using google map API to show Heat-map. After zooming one level, I want the heat-map area to show in the center of the map. I'm attaching the image also, it that you can see the heatmap at the bottom of the map.
render: function() {
var results = this.model.get('results');
if (!results)
return this;
var data = results[this.model.get('index')];
if (!data)
return this;
if (!data.data.length) {
data.data.push({
count: 0,
lat: 0,
lng: 0
});
}
showHeatMapData(data);
var startTime = this.model.get("starttm");
if(startTime >= 1436985000 && startTime <= 1437244199)
{
$("#pichart").show();
}
else
{
$("#pichart").hide();
}
this.heatmap.setData(data);
this.map.setZoom(20);
return this;
}
to zoom and fit the map to all the points:
this.heatmap.setData(data);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
bounds.extend(data[i]);
}
this.map.fitBounds(bounds);
i am guessing you have a longitude and latitude contains array
somethings looks like
var locationarray = [];
locationarray[0] = new google.maps.LatLng(13.74428, 100.5404525);
locationarray[1] = new google.maps.LatLng(13.744108, 100.543098);
now when you done loading other functions, you can just simply set the map center from your location array, like this
map.setCenter(locationarray[0]);
i hope this will help you.
Try this:
this.heatmap.setData(data);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
bounds.extend(data[i]);
}
this.map.setCenter(bounds.getCenter());
this.map.setZoom(20);

Categories