Dynamic Contents in Maps V2 Infowindow

Dynamic contents in Maps V2 InfoWindow

You should be doing Marker.showInfoWindow() on marker that is currently showing info window when you receive model update.

So you need to do 3 things:

  1. create model and not put all the downloading into InfoWindowAdapter
  2. save reference to Marker (call it markerShowingInfoWindow)

    from getInfoContents(Marker marker)
  3. when model notifies you of download complete call
if (markerShowingInfoWindow != null && markerShowingInfoWindow.isInfoWindowShown()) {
markerShowingInfoWindow.showInfoWindow();
}

Display dynamic content inside Google Map infowindow

http://jsfiddle.net/wf9a5m75/8xvgdwzu/2/

var geocoder = new google.maps.Geocoder();
var marker;
var infoWindow;
var map;

function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setLocation();
}

function setLocation() {
var address = '2349 Marlton Pike W, Cherry Hill, NJ 08002';
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
marker = new google.maps.Marker({
map: map,
position: position,
title: 'Venue Name'
});
map.setCenter(marker.getPosition());

var content = document.createElement('div');
var div = document.createElement('div');
div.id = "c_050e3e9d159498c53e6f88b44fad6987";
div.class = "normal";
content.appendChild(div);

var h2 = document.createElement('h2');
h2.style.color = "#000000";
h2.style.margin = "0 0 3px";
h2.style.padding = "2px";
h2.style.font = "bold 13px/1.2 Verdana";
h2.style.textAlign = "center";
h2.style.width = "100%";
div.appendChild(h2);

var a = document.createElement("a");
a.href = "http://www.forecast.co.uk/largs.html";
a.style.color = "#000000";
a.style.textDecoration = "none";
a.style.font = "bold 13px/1.2 Verdana";
a.innerText = "Forecast Largs";
div.appendChild(a);

var anotherDiv = document.createElement('div');
anotherDiv.id = "w_050e3e9d159498c53e6f88b44fad6987";
anotherDiv.class = "normal";
anotherDiv.style.height = "100%";
content.appendChild(anotherDiv);

var script = document.createElement('script');
script.src = "http://www.forecast.co.uk/widget/loader/050e3e9d159498c53e6f88b44fad6987";
content.appendChild(script);

infoWindow = new google.maps.InfoWindow({
content: content
});

google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});

//infoWindow.open(map, marker); doesn't work
google.maps.event.trigger(marker, 'click'); //still doesn't work
} else {
//
}
});
}

initialize();
//google.maps.event.addDomListener(window, 'load', initialize);

Sample Image

How to show dynamic content in @angular/google-maps infoWindow

Use ViewChildren, use index in the for loop in the template, pass in the index when marker is clicked, loop through all ViewChildren using an index inside of a forEach (for loop with index will not open the window for some reason), then if the index of the loop matches the index passed in, open that window. It seems like there would be a better way than this but it's all I could come up with after trying many things:

In component:

@ViewChildren(MapInfoWindow) infoWindowsView: QueryList<MapInfoWindow>;

openInfoWindow(marker: MapMarker, windowIndex: number) {
/// stores the current index in forEach
let curIdx = 0;
this.infoWindowsView.forEach((window: MapInfoWindow) => {
if (windowIndex === curIdx) {
window.open(marker);
curIdx++;
} else {
curIdx++;
}
});
}

In template:

<google-map height="400px"
width="750px"
[center]="center"
[zoom]="zoom">
<map-marker #marker
*ngFor="let place of places; let i = index" <-- added index -->
[position]="{ lat: place.latitude, lng: place.longitude }"
[options]="markerOptions"
(mapClick)="openInfoWindow(marker, i)"> <-- pass in index -->

<map-info-window>
{{ place.description }}
</map-info-window>
</map-marker>
</google-map>

This will open the info window with its respective marker.

Display dynamic content in Google Map infowindow

I'm not sure adding what's essentially just a <script> tag as the content of an infowindow is going to work. Instead I think you'd need to add that script file into your page (perhaps hidden somehow), then read the content of that div, and add that into the infowindow's content. Something like:

var script = document.createElement('script');
script.src = "https://www.tidetimes.org.uk/grimsby-tide-times.js";
$('#someDiv').appendChild(script);

infoWindow = new google.maps.InfoWindow({
content: $('#someDiv').html();
});

Dynamic marker and infoWindow Google Maps API using Google App Engine parsing through a JSON file

There are a few issues in your code. You should read Using Closures in Event Listeners.

  1. You should set the infowindow content on marker click (not within the loop, as you did)
  2. You should declare the marker variable which is missing
  3. Any variable you are using must be declared, for example for (element in data) should be for (var element in data)

function initMap() {
var myLatLng = { lat: 26.967, lng: -99.25 };
var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: myLatLng });
$.ajax({ type: 'GET', url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow', success: function(data) { data = JSON.parse(data)
console.log(data); infowindow = new google.maps.InfoWindow();
for (var element in data) { var marker = new google.maps.Marker({ position: { lat: data[element].lat, lng: data[element].lon }, map: map, title: element });
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country; content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content); infowindow.open(map, marker); }
})(marker, element)); } } });}
initMap();
#map {  height: 180px;}
<div id="map"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><!-- Replace the value of the key parameter with your own API key. --><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

Show dynamically to InfoWindow Googlemap V2

You would have to create additional data structure to hold your images, e.g.:

Map<Marker, Drawable> allMarkersMap = new HashMap<Marker, Drawable>();

after you add marker to GoogleMap:

allMarkersMap.put(marker, iImages);

in getInfoContents:

Drawable iImages = allMarkersMap.get(marker);

and add it to the ImageView.

Another way would be to use Android Maps Extensions, which has methods like Marker.setData(Object) and Object Marker.getData(). This you can use to directly assign Drawable to marker, just like you do with snippet.

How to dynamically add infowindows to markers on a google map?

The issue is that you shouldn't be referencing "i" in your event listener. When you click on a marker i is markers.length. The following event listener will work:

    google.maps.event.addListener(markers[i], 'click', function() {
this.infowindow.open(map, this);
});

Here is a code snippet to demonstrate:

<!DOCTYPE html xmlns:xlink="http://www.w3.org/1999/xlink">>
<head lang="en"> <meta charset="UTF-8"> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script> <script> var map; var markers = []; var contentString = '<h1>This is the Title!</h1>';
function initialize() { var losAngeles = new google.maps.LatLng(34.0500, -118.2500); var mapOptions = { zoom: 10, center: losAngeles, disableDefaultUI: true, mapTypeControlOptions: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); addMarkers(); }
function addMarker(location) { var markerOptions = { position: location, map: map } var marker = new google.maps.Marker(markerOptions); markers.push(marker); }
var locations = [{ start: "2015-04-10", lat: 34.0500, lng: -118.2500 }];
function addMarkers() { for (var i = 0; i < locations.length; i++) { if (locations[i].start.slice(0, 10) == "2015-04-10") { addMarker(new google.maps.LatLng(parseFloat(locations[i].lat), parseFloat(locations[i].lng))); } }
for (var i = 0; i < markers.length; i++) { markers[i].infowindow = new google.maps.InfoWindow({ content: contentString }); google.maps.event.addListener(markers[i], 'click', function() { this.infowindow.open(map, this); }); } }
google.maps.event.addDomListener(window, 'load', initialize); </script></head>
<body> <div id="map-canvas"></div></body>
</html>

Google Maps Infowindow with dynamic data

One option is to get function closure on the address in the showGeocodedAddressOnMap function.

var showGeocodedAddressOnMap = function(address, asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
var markersArray = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
// icon: icon
});
google.maps.event.addListener(markersArray, 'click', function(evt) {
infowindow.setContent('<strong>Address</strong><br /><br />' + address + '<br /><br /><strong>Distance:</strong> ');
infowindow.open(map, this);
});
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};

proof of concept fiddle

code snippet:

function initialize() {  map = new google.maps.Map(    document.getElementById("map_canvas"), {      center: {        lat: 55.53,        lng: 9.4      },      zoom: 10,      mapTypeId: google.maps.MapTypeId.ROADMAP    });
var service = new google.maps.DistanceMatrixService; service.getDistanceMatrix({ origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: 'DRIVING', unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false }, callback);}
function callback(response, status) { if (status == "OK") { var originList = response.originAddresses; var destinationList = response.destinationAddresses; var bounds = new google.maps.LatLngBounds; var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(address, asDestination) { return function(results, status) { if (status === 'OK') { map.fitBounds(bounds.extend(results[0].geometry.location)); var markersArray = new google.maps.Marker({ map: map, position: results[0].geometry.location, }); google.maps.event.addListener(markersArray, 'click', function(evt) { infowindow.setContent('<strong>Address</strong><br /><br />' + address + '<br /><br /><strong>Distance:</strong> '); infowindow.open(map, this); }); } else { alert('Geocode was not successful due to: ' + status); } }; };
for (var i = 0; i < originList.length; i++) { var results = response.rows[i].elements; geocoder.geocode({ 'address': originList[i] }, showGeocodedAddressOnMap(originList[i], false)); for (var j = 0; j < results.length; j++) { geocoder.geocode({ 'address': destinationList[j] }, showGeocodedAddressOnMap(destinationList[j], true)); } } } else { alert("Error: " + status); }}google.maps.event.addDomListener(window, "load", initialize);
var geocoder;var map;var origin1 = { lat: 55.93, lng: -3.118};var origin2 = 'Greenwich, England';var destinationA = 'Stockholm, Sweden';var destinationB = { lat: 50.087, lng: 14.421};var geocoder = new google.maps.Geocoder();var infowindow = new google.maps.InfoWindow();
html,body,#map_canvas {  height: 100%;  width: 100%;  margin: 0px;  padding: 0px}
<script src="https://maps.googleapis.com/maps/api/js"></script><div id="map_canvas"></div>


Related Topics



Leave a reply



Submit