infowindow.setContent shows only one record - javascript

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);
}

Related

Changing google maps marker property after clicking button inside info window

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);
});

Proper formatting and distribution on multiple events for a jquery button click?

For now, on a button click I have it so that it takes in data from two textboxes, and uses it to
1) append tweets to a panel, and
2) drop pins on a map.
My next step is to have it so that on the button click, it geodecodes a location, and does the same thing. I feel like my jquery.click function is getting really big, and wanted to know if there was a standard way to "separate" it out to make it look prettier and more readable. Can you typically have javascript functions within a jquery file that are called upon, or what is the way to go?
Here is my current jquery file. As you can see it's very big but what happens is straight forward: searchbutton on click takes some values, and sets up a new map in that location, then I access my web server's information, append it to a panel, and also drop pins on a map.
$(function () {
$("#search-button").click(function() {
// variables for google maps
var LatValue = parseFloat($("#searchLat").val());
var LonValue = parseFloat($("#searchLon").val());
var myLatLng = {lat: LatValue, lng: LonValue};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: myLatLng
});
$.getJSON(
"http://localhost:3000/tw",
{
geoSearchWord: $("#searchme").val(),
geoSearchWordLat: $("#searchLat").val(),
geoSearchWordLon: $("#searchLon").val(),
geoSearchWordRad: $("#searchRadius").val()
}
).done(function (result) {
$("#fromTweets").empty();
console.log(result);
for (i = 0; i < result.statuses.length; i++) {
//Print out username and status
$("#fromTweets").append('<b>' + "Username: " + '</b>' + result.statuses[i].user.screen_name + '<br/>');
$("#fromTweets").append('<b>' + "Tweet: " + '</b>' + result.statuses[i].text + '<br/>');
$("#fromTweets").append('<b>' + "Created at: " + '</b>' + result.statuses[i].created_at + '<br/>');
if (result.statuses[i].geo !== null) {
//Print out the geolocation
$("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Lat: " + result.statuses[i].geo.coordinates[0] + " Lon: " + result.statuses[i].geo.coordinates[1] + '<br/>'+ '<br/>');
//dropping a new marker on the map for each tweet that has lat/lon values
//Multiplying by i * 0.0005 to space them out in case they are from the same gelocation while still holding
//the integrity of their location.
LatValue = parseFloat(result.statuses[i].geo.coordinates[0] + i*0.0005);
LonValue = parseFloat(result.statuses[i].geo.coordinates[1] + i*0.0005);
myLatLng = {lat: LatValue, lng: LonValue};
var newMarker = new google.maps.Marker({
position: myLatLng,
map: map,
animation: google.maps.Animation.DROP,
});
} else {
$("#fromTweets").append('<b>' + "GeoLocation: " + '</b>' + "Cannot be identified" + '<br/>' + '<br/>')
}
}
});
});
The most simple and obvious thing you can do it so split your code by extracting independent logical blocks to functions:
Just something like this:
var map;
function combineTweetsAjaxRequestData()
{
return {
geoSearchWord: $("#searchme").val(),
geoSearchWordLat: $("#searchLat").val(),
geoSearchWordLon: $("#searchLon").val(),
geoSearchWordRad: $("#searchRadius").val()
};
}
function createGMap()
{
return new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {
lat: parseFloat($("#searchLat").val()),
lng: parseFloat($("#searchLon").val())
}
});
}
function createGMarker(coords)
{
var coordsFixed = {
lat: parseFloat(coords[0] + i * 0.0005),
lng: parseFloat(coords[1] + i * 0.0005)
};
return new google.maps.Marker({
position: coordsFixed,
map: map,
animation: google.maps.Animation.DROP,
});
}
function clearInfo() {
$("#fromTweets").empty();
}
function appendInfo(title, text)
{
$("#fromTweets").append('<b>' + title + ':</b> ' + text + '<br/>');
}
function processTweet(tw)
{
appendInfo('Username', tw.user.screen_name);
appendInfo('Tweet', tw.text);
appendInfo('Created at', tw.created_at);
if (tw.geo !== null) {
var twCoords = tw.geo.coordinates;
appendInfo('GeoLocation', "Lat: " + twCoords[0] + " Lon: " + twCoords[1]);
createGMarker(twCoords);
} else {
appendInfo('GeoLocation', "Cannot be identified")
}
}
function loadTweets() {
$.getJSON(
"http://localhost:3000/tw",
combineTweetsAjaxRequestData()
).done(function (result) {
clearInfo();
console.log(result);
result.statuses.forEach(processTweet);
});
}
$(document).ready(function () {
map = createGMap();
$("#search-button").click(function() {
loadTweets();
});
});
Now, it can be easily read as a text. Your code should be readable and understandable from the first glance. Even better, if a non-developer can read it and understand some basic concepts.
What happens when the page is loaded? We create a Google map control and load tweets
How do we load tweets? We make a AJAX request by combining request data from inputs
What happens when it is loaded? We clear out current information and process every tweet
How do we process a single tweet? We output some basic information. Then, we output geolocation if it is available. Otherwise, we output an error.
Now, if you need to add information to another source, you won't extend or modify your loadTweets method - you will extend or modify appendInfo method, because the logics of information output is encapsulated here.

gmap api v3 infowindow html string content not showing

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

Google Maps: get lat/lng from geocoded postcode

I am currently plotting multiple points on a map, using addresses from an object. The program loops over the object, geocodes the address, and plots a marker for each location.
The problem I am having is when a user clicks on a place in a list, the map is to pan to that location. The API has a panTo() function that accepts lat, lng values, but the results, i.e. results[0].geometry.location, from the geocode function are not available outside of it.
Question
How do I somehow retrieve the lat, lng from the results, maybe append them to the existing data object, and use them outside the function, so I am able to use them in the panTo() function?
[The lat/lng values are output in html data attributes]
Click handler
$('.place').on('click', function() {
$this = $(this);
lat = $this.data('lat');
lng = $this.data('lng');
map.panTo(new google.maps.LatLng(lat, lng));
});
Data
var locations = [
{
id: 'place1',
postcode: 'B1 1AA'
},
{
id: 'place2',
postcode: 'CB9 8PU'
}
];
Code
for (i = 0; i < locations.length; i++) {
geocoder.geocode({'address': locations[i].postcode}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
console.log('Geocode was not successful ' + status);
}
}); // end geocode
$(places).append(
'<li class="place" data-id="'+locations[i].id+'" data-lat="<!--lat to go here-->" data-lng="<!--lng to go here-->">'+
'<div class="place-wrap">'+
'<h2>'+locations[i].name+'</h2>'+
'<p class="territory">'+locations[i].territory+'<p>'+
'</div>'+
'</li>'
);
} // end for
Give this a go. The IIFE is there to enclose the index so you don't keep hitting the last index of the locations array due to the asynchronous nature of geocode.
for (i = 0, l = locations.length; i < l; i++) {
(function(i) { // index passed in as parameter
geocoder.geocode({ address: locations[i].postcode }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
$('#places').append(
'<li class="place" data-id="' + locations[i].id + '" data-lat="' + results[0].geometry.location.lat() + '" data-lng="' + results[0].geometry.location.lng() + '">' +
'<div class="place-wrap">' +
'<h2>' + locations[i].name + '</h2>' +
'<p class="territory">' + locations[i].territory + '<p>'+
'</div>' +
'</li>'
);
} else {
console.log('Geocode was not successful ' + status);
}
});
}(i)); // index passed in to IIFE
}

Google Maps API V3 Search KML File

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.

Categories