I've a problem with pushing array html content into an infowindow:
I whant to try to append a html string for each marker that i customize via javascript into the Map, the code work with a native infowindow, but when i try to append html the infowindow is empty.
Here the code:
function initialize(markerPlaces) {
(function(window, google, maplib){
var mapOptions = maplib.MAP_OPTIONS,
domElement = document.getElementById('map'),
//map declaration
map = new google.maps.Map(domElement, mapOptions);
console.log(markerPlaces);
var contentStringOpen = '<div class="modul1 modalWindow">';
var contentStringMiddle = '<span class="modul1_txt">';
var contentStringClose = '</span></div>';
var infowindow = new google.maps.InfoWindow();
var contArray = new Array();
for(i=0;i<markerPlaces[0].posts.length;i++){
var thumb = markerPlaces[0].posts[i].thumb;
var title = markerPlaces[0].posts[i].title;
contArray.push('' +
'<div id="' + markerPlaces[0].posts[i].postId +
'" class="modul1 modalWindow">' +
markerPlaces[0].posts[i].thumb +
'<span class="modul1_txt">' +
markerPlaces[0].posts[i].title +
'</span></div>');
markers = new google.maps.Marker({
position: {
lat: Number(markerPlaces[0].posts[i].lat),
lng: Number(markerPlaces[0].posts[i].long)
},
map: map,
icon: 'http://tovisit.today/wp-content/themes/turisti/img/poi.png',
title: markerPlaces[0].posts[i].title
})
console.log(contArray[i]);
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
//switch this for htmlContent
//infowindow.setContent(contArray[i]);
//this work
infowindow.setContent(contentStringMiddle + markerPlaces[0].posts[i].title + contentStringClose + markerPlaces[0].posts[i].thumb);
infowindow.open(map, markers);
$()
}
})(markers, i));
}
}(window, google, window.maplib || (window.maplib = {})));
}
The content string is correct:
but when i ispect the dom the div.modalWindow, and his content, missing
anyone has the same trouble?
i solve the problem, sometime a display:none cause some trouble, i forgot this debug css line, i apologize for loosinrg your time.
The function is correct and work by the way.
Thank U for the -1 have a nice day
Related
I have error when I load my page: https://www.cupsubito.it/dove-siamo
I don't kwon because about this error. Thank you very much for helping.
Thanks for help me!
The code JS is:
let _locations = [];
var elenco;
google.maps.visualRefresh = true;
var slider, infowindow = null;
var bounds = new google.maps.LatLngBounds();
var current = 0;
var map = 0;
var icons = {
//'default': '/assets/img/marker.png'
};
function showMap() {
infowindow.close();
if (!map.slide) {
return;
}
var next, marker;
if (_locations.length == 0) {
return
} else if (_locations.length == 1) {
next = 0;
}
if (_locations.length > 1) {
do {
next = Math.floor(Math.random() * _locations.length);
} while (next == current)
}
current = next;
marker = _locations[next];
setInfo(marker);
//infowindow.open(map, marker);
}
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(42.4053848, 12.4276547),
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
map.slide = true;
//setMarkers(map, _locations);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
google.maps.event.addListener(infowindow, 'closeclick', function () {
infowindow.close();
});
slider = window.setTimeout(showMap, 3000);
}
function setInfo(marker) {
var content =
'<div class="profile-widget" style="width: 100%; display: inline-block;">' +
'<div class="doc-img">' +
'<a href="' + marker.profile_link + '" tabindex="0" target="_blank">' +
'<img class="img-fluid" alt="' + marker.doc_name + '" src="' + marker.image + '">' +
'</a>' +
'</div>' +
'<div class="pro-content">' +
'<h4 class="text-center">' +
'' + marker.doc_name + '' +
'</h4>' +
'<ul class="available-info pt-5">' +
'<li><i class="fas fa-map-marker-alt"></i> ' + marker.address + ' </li>' +
'</ul>' +
'</div>' +
'</div>';
infowindow.setContent(content);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var item = markers[i];
var latlng = new google.maps.LatLng(item.lat, item.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
doc_name: item.doc_name,
address: item.address,
speciality: item.speciality,
profile_link: item.profile_link,
animation: google.maps.Animation.DROP,
icon: icons[item.icons],
image: item.image
});
bounds.extend(marker.position);
markers[i] = marker;
google.maps.event.addListener(marker, "click", function () {
setInfo(this);
infowindow.open(map, this);
window.clearTimeout(slider);
});
}
map.fitBounds(bounds);
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.zoom > 16) map.slide = false;
});
// Add a marker clusterer to manage the markers.
new markerClusterer.MarkerClusterer({ markers, map });
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function () {
$.ajax({
url: "?handler=ElencoStrutture",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: elenco,
contentType: "application/json; charset=utf-8",
success: function (data) {
//console.error(data.ElencoStrutture);
_locations = data.ElencoStrutture;
setMarkers(map, _locations);
slider = window.setTimeout(showMap, 3000);
//alert("done ELENCO STRUTTURE");
}
});
});
Sometimes it works and sometimes it doesn't, I don't understand why it doesn't always work.
The problem is that it usually works the first time, so I don't understand where I'm wrong on the code side.
The map should display all pointers correctly and instead it sometimes shows me a blank map with this error.
I added part of code where I load setMarkers(map, _locations) for to have more informations.
thank you very much for answers.
I hope I have added useful information to my problem, I don't understand why it sometimes works and sometimes it doesn't.
I am working on a project in Laravel.
This is my script that I have done to display a map with multiple markers with Google Maps. I have 2 json objects that I am retrieving one with the locations and one with autos. A location can have many autos, so it is a one to many relationship.
What i am trying to do is that in the infowindow.setContent to display a description of the location and the autos that belong to the location.
The map, the markers with the proper locations are displayed correctly. But in the infowindow.setContent are displayed the description and the title of the location and the last record of the autos that belong to that location.
When the script is run the console.log displays the information as it has to be. that means that my loop for autos is working fine but when i pass the result to the infowindow.setContent it reads only the last record.
This is my first time asking for help here, so excuse me if I'm not clear enough. I would be very grateful to anyone that responds to me.
My Script:
<script type="text/javascript">
var locations = #json($locations);
var autos = #json($autos);
var infowindow = new google.maps.InfoWindow();
var mymap = new GMaps({
el: '#mymap',
center: {lat: 41.323029, lng: 19.817856},
zoom:6
});
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
var autoBrands =autos[auto].brand;
console.log(autoBrands);
}
}
infowindow.setContent('<div><strong>' + autoBrands + '</strong><br></div>'+ '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>');
infowindow.open(mymap, this);
}
});
});
</script>
It looks like you just reassigning value of autoBrands inside your loop. Why don't you create it as an array object? Something like
<script type="text/javascript">
var locations = #json($locations);
var autos = #json($autos);
var infowindow = new google.maps.InfoWindow();
var mymap = new GMaps({
el: '#mymap',
center: {lat: 41.323029, lng: 19.817856},
zoom:6
});
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
var autoBrands = [];
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
autoBrands.push(autos[auto].brand);
console.log(autoBrands);
}
}
infowindow.setContent('<div><strong>' + autoBrands.join(",") + '</strong><br></div>'+ '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>');
infowindow.open(mymap, this);
}
});
});
Hope this helps!
You're looping over all your locations, adding a marker for each. However you only have one infowindow variable. On each iteration of the loop, you're updating what the content of the same infowindow will be, so it ends up just getting the content from the very last iteration.
Have a separate function that opens the infowindow in response to the user's click, something like this:
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.lat,
lng: value.long,
title: value.title,
click: function(e) {
for (var auto in autos)
{
if(autos[auto].location_id == value.id)
{
var autoBrands =autos[auto].brand;
console.log(autoBrands);
}
}
openInfowindow(
'<div><strong>' + autoBrands + '</strong><br></div>'+ '<div><strong>' + value.title + '</strong><br></div>' + '<div><strong>' + value.description + '</strong><br></div>',
this
);
}
});
});
function openInfowindow(content, marker)
{
infowindow.setContent(content);
infowindow.open(mymap, marker);
}
I have markers on a map. I set the opacity of the marker dependent on the date in JSON.
Because of this when the map loads, some of the markers are 0.5 opacity, some are 1 opacity.
Inside the marker's info window there is a button. When I click this button I want to change the opacity to 1.
Below is some snippets of my code to show you how I have it setup at the moment.
Any help would be much appreciated
//For every item in JSON
$.each(dbJSON, function(key, data) {
var opacity = 1;
var today = new Date();
var fadeDate = new Date(data.last_rated); //get the date last rated
fadeDate.setDate(fadeDate.getDate() + 1); //and add 1 date to it to specify the day when the icon should fade
if(Date.parse(today) > Date.parse(fadeDate)) {
console.log('fade');
opacity = 0.5;
} else {
console.log('show');
opacity = 1;
}
var postal_town = data.location;
geocoder.geocode( { 'address': postal_town}, function(results, status) {
//...
console.log(opacity);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data.manufacturer_name,
icon: image,
rating: data.rating,
opacity: opacity
});
markers[data.id] = marker;
marker.addListener('click', function() {
var contentString = '<div id="content">'+
'<h1>' + data.manufacturer_name + '</h1>' +
'<button id="seen-it" data-rating="' + data.rating + '" data-entry-id="' + data.id + '">Seen it</button>' +
'<p><strong>Rating: </strong><span id="rating">' + markers[data.id].rating + '</span></p>' +
'</div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
});
});
//Do something when the #seen-it button is clicked
$(document).on('click', '#seen-it', function(event){
//...
});
Since you have the id of the marker stored in the data-entry-id you could use (assuming the markers variable is accessible from your handler)
$(document).on('click', '#seen-it', function(event){
var markerId = $(this).data('entry-id');
markers[markerId].setOpacity(1);
});
I'm trying to create a group of markers with info box attached. However, no matter which marker I click, it always opens the info box of the last detailmarker. Anyone know why? Please help.
var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
var markers = [];
for (var i = 1; i < itinerary.Legs.length; i++) {
var position = new google.maps.LatLng(itinerary.Legs[i].BusStop.Latitude, itinerary.Legs[i].BusStop.Longitude);
var title = itinerary.Legs[i].BusStop.Code + ": " + itinerary.Legs[i].BusStop.Location + " " + itinerary.Legs[i].BusStop.Street + ", Quận " + itinerary.Legs[i].BusStop.Ward;
var detailmarker = new google.maps.Marker({
position: position,
map: map,
title: title,
icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
});
google.maps.event.addListener(detailmarker, 'click', function () {
stepDisplay.setContent(title);
stepDisplay.open(map, detailmarker);
});
markers[i-1] = detailmarker;
}
}
Edit: possible dublicate of Google maps infowindow showing on wrong marker. I've tried all the solutions I found here and none works.
Yes, this is exactly the same problem as the other one you linked to, and the solution for your code is the same - put the code to create each marker into a function, and call that function in your loop:
var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
for (var i = 1; i < itinerary.Legs.length; i++) {
addLegMarker( map, itinerary.Legs[i] );
}
}
function addLegMarker( map, leg ) {
var position = new google.maps.LatLng(leg.BusStop.Latitude, leg.BusStop.Longitude);
var title = leg.BusStop.Code + ": " + leg.BusStop.Location + " " + leg.BusStop.Street + ", Quận " + leg.BusStop.Ward;
var detailmarker = new google.maps.Marker({
position: position,
map: map,
title: title,
icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
});
google.maps.event.addListener(detailmarker, 'click', function () {
stepDisplay.setContent(title);
stepDisplay.open(map, detailmarker);
});
}
Do you see why that fixes it? The title and detailmarker are now specific to each invocation of addLegMarker(). In the original code, there was only a single copy of each of these variables, shared among all markers.
I am wanting to search a KML file to see if a particular address falls within an overlay. Presently, I have the address converting to a geocode. However, I'm not sure what code is needed to add this functionality.
Here's the present code:
function initialize() {
var infowindow = new google.maps.InfoWindow({
content: '',
suppressMapPan:true
});
var myLatlng = new google.maps.LatLng(35.910200,-84.085100);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), myOptions);
var d = new Date();
var n = d.getMilliseconds();
var nyLayer = new google.maps.KmlLayer(
'http://www.cspc.net/neighborhoods/groups.kml?rand=' + n,
{ suppressInfoWindows: true, map: map});
google.maps.event.addListener(nyLayer, 'click', function(kmlEvent) {
var url = kmlEvent.featureData.snippet;
var groupName = kmlEvent.featureData.name;
var insideContent = "<div style='width:250px;'><h2>" + groupName +
"</h1><p>We have a neighborhood contact in your area! </p>" +
"<p><a href='" + url + "' target='_blank'>Get connected!</a>" +
" They look forward to hearing from you.</p><p>If you have " +
"any additional questions, please contact our " +
"<a href='http://www.cspc.net/communitylife' target='_blank'>" +
"Community Life</a> staff for more information. Betsy Palk, " +
"the Administrative Assistant, may be reached at:<br/><br/>" +
"<b>Email:</b> <a href='mailto:betsypalk#cspc.net'>" +
"betsypalk#cspc.net</a><br/><b>Phone:</b> 865-291-5268<p></div>";
var clickPos = kmlEvent.latLng;
var posX = new google.maps.LatLng(clickPos.lat(), clickPos.lng());
infowindow.close();
infowindow.setPosition(posX);
infowindow.setContent(insideContent);
infowindow.open(map);
});
eventMapClick = google.maps.event.addListener(map, 'click',
function(event) {
var marker = new google.maps.Marker({ position: event.latLng });
var outsideContent = "<div style='width:250px;'><h2>Oops!</h1>" +
"<p> It seems we don't have a neighborhood contact in your " +
"area.</p><p>Please contact our <a " +
"href='http://www.cspc.net/communitylife' target= '_blank'>" +
"Community Life</a> staff for more information. " +
"Betsy Palk, the Administrative Assistant, may be reached at:" +
"<br/><br/><b>Email: </b> <a href='mailto:betsypalk#cspc.net'>" +
"betsypalk#cspc.net</a><br/><b>Phone:</b> 865-291-5268<p></div>";
infowindow.setContent(outsideContent);
infowindow.open(map, marker);
});
}
var geocoder = new google.maps.Geocoder();
function searchAddress(address) {
geocoder.geocode(
{'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
// use loc.lat(), loc.lng()
window.alert(loc);
}
else {
window.alert("Not found: " + status);
}
}
);
};
If I understand your question, I believe you want the formula to determine if a point (google.maps.LatLng) falls within one of your KML Placemark definitions (that you give names such as: Neighborhood Group 1). Within each Placemark, you define a Polygon and within each Polygon, you define a set of coordinates, which represent the vertices of the Polygon.
Using the coordinates within the Polygon and the LatLng you retrieve via geocoding, you could start with these formulas and select that one that is the best fit for you:
Fast Winding Number Inclusion of a Point in a Polygon
Point-In-Polygon Algorithm
A very similar question has also been asked here on SO: Determine the lat lngs of markers within a polygon.