I am having trouble trying to display the event name from an array of objects in a parsed JSON file within Google Maps Ionic framework. Right now I have the markers displaying for each event with a simple string called "testing" which displays fine. The problem is I am unsure of how to display each events name within this info window and not the string I made. Any help would be appreciated. I'll post the sample image I have now as well as the info window functionality below. Thanks!
what I have displaying now:
here
marker/info window functionality:
getMarkers(){
//this.http.get('assets/data/markers.json').map((res)=>res.json()).subscribe(data=>{
this.http.get('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500').map((res)=>res.json()).subscribe(data=>{
this.addMarkersMap(data);
});
}
addMarkersMap(markers){
for(let marker of markers)
{
var loc = marker.calEvent.locations[0]['coords'];
console.log(loc);
marker = new google.maps.Marker({
position: loc,
map: this.map,
});
var infoWindow = new google.maps.InfoWindow({
content: markers.eventName
});
google.maps.event.addListener(marker, 'click', function(str)
{
return function() {
infoWindow.setContent(str);
infoWindow.open(this.map, marker);
}
}(markers.eventName));
}
}
I correct myself. You could benefit from a closure here.
Use a self-calling function to seal your parameter to the infowindow:
google.maps.event.addListener(marker, 'click', function(str)
{
return function() {
infoWindow.setContent(str);
infoWindow.open(this.map, marker);
}
}(markers.calEvent.eventName));
Related
How can I put the type of addListener of google maps onto Mapbox instead of below one?
Thanks for the response!
stationI.addListener('click', function() {
SetStationInfo(this.title);
});
Herebelow is the full code:
for (var i=0;i<APIinfo.network.stations.length;i++){
popup = new mapboxgl.Popup({ offset: 25 })
.setText(APIinfo.network.stations[i].name); //Mapbox
var marker = new mapboxgl.Marker()
.setPopup(popup)
.setLngLat([APIinfo.network.stations[i].longitude, APIinfo.network.stations[i].latitude])
.addTo(map); //Mapbox
stationI.addListener('click', function() { //Google Maps
SetStationInfo(this.title);
});
}
Reading your code, not sure what stationI is, if it's a layer or an object.
But regarding the events in mapbox, you can do that with:
map.on('click', function(e) {
console.log('A click event has occurred at ' + e.lngLat);
});
you can also add the layer:
map.on('click', 'yourLayerId', function(e) {
console.log('A click event has occurred at ' + e.lngLat);
});
I have implemented a custom overlay. I want to add an event which will pop an info window when I click the overlay.
function initMap() {
var map = new google.maps.Map(document.getElementById('okmap'), {
zoom: 4,
center: {lat: 35.0000, lng: 103.0000}
});
for (var n in nodes) {
var myMarker = new MyMarker(map, {latlng: new google.maps.LatLng(nodes[n][0], nodes[n][1]),
image: 'assets/img/light-green.png',
labelText: (Math.random() * 100).toFixed(0)});
markers.push(myMarker);
var infowindow = new google.maps.InfoWindow({
content: n
});
myMarker.addListener('click', function() {
infowindow.open(map, myMarker);
});
}
}
But it is not working!
I faced a simliar problem some time back. Here are two things that helped me.
I am considering the main overlay element to be a div.
In your MyMarker.draw function make sure that you are using a pane that has access to the DOM events.e.g.
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(div);
See https://developers.google.com/maps/documentation/javascript/customoverlays#initialize for more details.
Make sure you define an event listener, also in the MyMarker.draw function.
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(self, "click");
});
I'm trying to show different maps in different views but charging 1 on 1 map view, switch to another map not load, there is no mistake to launch the browser so I could not decide because I can not keep showing other maps. I'm doing as follows:
$scope.cargarUbicacion = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
latitud_actual = position.coords.latitude;
longitud_actual = position.coords.longitude;
console.log(latitud_actual);
console.log(longitud_actual);
var mapOptions = {
center: new google.maps.LatLng(latitud_actual, longitud_actual),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("mapa_ubicacion"), mapOptions);
$scope.setMarker(map, new google.maps.LatLng(latitud_actual, longitud_actual), 'Yo', '');
});
}
}
$scope.setMarker = function(map, position, title, content) {
var marker;
var markerOptions = {
position: position,
map: map,
title: title,
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
};
marker = new google.maps.Marker(markerOptions);
markers.push(marker); // add marker to array
google.maps.event.addListener(marker, 'click', function () {
// close window if not undefined
if (infoWindow !== void 0) {
infoWindow.close();
}
// create new window
var infoWindowOptions = {
content: content
};
infoWindow = new google.maps.InfoWindow(infoWindowOptions);
infoWindow.open(map, marker);
});
}
I am using this code in multiple controllers, my idea is encapsulated and can occupy the same code 1 time in several views. Whenever I change the id map to avoid that problem, thinking that this was the cause that did not load the map.
Any idea how to do what I need or that is failing to load maps?
Thank you.
I personnaly do the following :
The code taht you want to reuse put it into a global variable such as :
Then into your control, you can extend it with this mapExtend
global.MapExtend = function($scope, $rootScope, leafletData) {
// ... all your functions to reuse
};
// In your main controler, extend it with your map capabilities with angular.extend
angular.extend(myCtrl, new MapExtend($scope, $rootScope, leafletData));
I'm trying to display markers on a map, but I am running in to difficulty, I'm not too skilled in the use of callbacks, can someone help me out thanks? I want multiple markers to show where different games are.
I'm using a rest api to retrieve the game details from the db, and I know this works, it's just after I retrieve them I can no longer access the data that has just been retrieved.
I am using ionic (Angular) and I am sure there is probably a better way of doing this. What is the best way to use a loop? If anyone could point out how I could improve my code. Here is what my controller for the map looks like
.controller('MapController', function($scope, $ionicLoading, gameFactory) {
$scope.initialise = function() {
...//set up map
});
$scope.map = map;
};
$scope.showGameMarkers = function() {
var map = document.getElementById("map");
gameFactory.getGames().success(function(data) {
//at this stage the data variable contains the details of my game
angular.forEach(data, function(key, data) {
//now data is empty
var latLng = new google.maps.LatLng(data.locationLatitude, data.locationLongitude);
console.log("latlang = "+latLng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.locationName,
setMap : map
});
});
}).error(function(data) {
console.log("no games");
});
};
google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.initialise());
google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.showGameMarkers());
});
Thank you in advance!
It looks like you might have your key and data parameters reversed in your forEach loop. According to https://docs.angularjs.org/api/ng/function/angular.forEach it should be
angular.forEach(values, function(value, key) {
...
}
With backbone I am fetching results from Google maps to return markers of places where the user is. The results populate a collection which I clear everytime the user moves the map as a new fetch occurs based on the new location bounds (I am using the google map idle event to get this information and changing the URL of the collection).
To manage the markers I populate an array with each marker.
The issue I am having is I get the first set of markers but it does not write in any new markers when the map is moved and when you inspect the markers array its the same results as last. If I do an AJAX call I get the desired results, but I want to keep this all within a backbone collection as I do other processes with the model.
/* Tracking Page Items */
var allPlace = Backbone.Model.extend({
createMarker:function(){
var marker = new google.maps.Marker({
position: this.getLatLng(),
title: this.get("name"),
location_type: this.get("type")
});
return marker;
}
});
var MarkersCollection = Backbone.Collection.extend({
model: allPlace,
url:function(){
return '/'
}
})
var markersArray = [];
var mapAll = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'createMarkers'); // get access to this in other methods
this.collection.bind('reset', this.render, this);
},
render: function() {
// Load map scripts and initialise
if(typeof google === "undefined"){
nzp.loadGoogleMap();
} else {
nzp.initializeMap();
};
// Current location
myLocations = {
lat: this.collection.lat,
lng: this.collection.lng
};
// Listen for map movement
var self = this;
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var lat1 = bounds.ca.b;
var lng1 = bounds.ea.b;
var lat2 = bounds.ca.f;
var lng2 = bounds.ea.f;
self.showMarkers(lat1, lng1, lat2, lng2);
});
},
// update URL based on new bround
showMarkers: function(lat1, lng1, lat2, lng2) {
var markerCollection = new MarkersCollection;
nzp.infoWindow = new google.maps.InfoWindow();
lat = myLatlng.Xa;
lng = myLatlng.Ya;
lat1 = lat1;
lng1 = lng1;
lat2 = lat2;
lng2 = lng2;
// Collection URL build from parameter adn current location
markerCollection.url = "http://blah.com/locator/api/locations?api_key=XXX&nearby_latitude="+lat+"&nearby_longitude="+lng+"&lat1="+lat1+"&lng1="+lng1+"&lat2="+lat2+"&lng2="+lng2+"&max=10&format=jsonp&callback=?";
// Fetch collection
markerCollection.fetch({
success: function(results) {
// Clear the markers array
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
// Loop over items in collection
results.map(function(item){
var marker = item.createMarker();
marker.setMap(map);
// Create a marker based on each item
(function(marker, item) {
google.maps.event.addListener(marker, "click", function(e) {
nzp.infoWindow.setContent(infowindowContent(item)); // Info window content is processed in a method within the model
nzp.infoWindow.open(map, marker);
});
// Place each marker in the markers arrya
markersArray.push(marker); // Push markers into an array so they can be removed
})(marker, item);
}, this);
}
});
// Set markers to vidsible
$.each(markersArray, function(index, item){
markersArray[index].setVisible(true);
});
});
Fixed this. The issue was related to the values being passed to the API and not how I was updating the collection URL as I thought.
I was passing a bounds and a current location and bounds which was causing the API to always return the same results. The working AJAX version I had of the code had a typo in the URL which actually allowed the API to return the correct results.