Google Maps API Multiple Marker InfoWindowContent showing same data - javascript

I have consoled the data and it is fine, I see the different names being consoled properly. the multiple markers are also being created but on the InfoWindow it is only showing the data for the last row for every Marker.
<?php
include 'connect.php';
$locations=array();
$apikey = "APIKEY";
$query = $db->query('SELECT * FROM fields');
while( $row = $query->fetch_assoc() ){
$name = $row['field_name'];
$longitude = $row['field_longitude'];
$latitude = $row['field_latitude'];
$owner = $row['field_owner'];
$incharge = $row['field_incharge_name'];
$contact_number = $row['contact_number'];
$field_address = $row['field_address'];
$field_pitch_length = $row['field_pitch_length'];
$field_pitch_breadth = $row['field_pitch_breadth'];
$ground_busy_hours_per_week = $row['ground_busy_hours_per_week'];
$locations[]=array('field_name'=>$name,'lat'=>$latitude,'lng'=>$longitude, 'owner'=>$owner, 'incharge'=>$incharge, 'contact_number'=>$contact_number, 'field_address'=>$field_address, 'field_pitch_length'=>$field_pitch_length, 'field_pitch_breadth'=>$field_pitch_breadth, 'ground_busy_hours_per_week'=>$ground_busy_hours_per_week);
}
$markers = json_encode($locations);
?>
<body>
<div id="map"></div>
<script>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 15.3489395, lng: 73.7347356},
mapTypeId: 'roadmap'
});
for(i = 0; i < markers.length; i++) {
var infoWindow = new google.maps.InfoWindow(), marker;
infoWindowContent = '<div class="info_content">' +
'<h4>Field Name: </h4><p>'+' '+markers[i].field_name+'</p><br>' +
'<h4>Owner: </h4><p>'+' '+markers[i].owner+'</p><br>' +
'<h4>Incharge: </h4><p>'+' '+markers[i].incharge+'</p><br>' +
'<h4>Contact No: </h4><p>'+' '+markers[i].contact_number+'</p><br>' +
'<h4>Field Address: </h4><p>'+' '+markers[i].field_address+'</p><br>' +
'<h4>Pitch Length: </h4><p>'+' '+markers[i].field_pitch_length+'</p><br>' +
'<h4>Pitch Breadth: </h4><p>'+' '+markers[i].$field_pitch_breadth+'</p><br>' +
'<h4>Busy Hours per Week: </h4><p>'+' '+markers[i].ground_busy_hours_per_week+'</p><br>' +
'</div>';
lat = parseFloat(markers[i].lat);
lng = parseFloat(markers[i].lng);
var position = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker) {
return function() {
infoWindow.setContent(infoWindowContent);
infoWindow.open(map, marker);
}
})(marker));
}
google.maps.event.addDomListener(window, 'load', initMap);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap">
</script>
</body>
Sorry cannot share the DB, maybe for testing you can use dummy data. I have no idea why it is only displaying the data from the last row.
Thanks for the help.

I think you need to pass the "infoWindowContent" also to the closure.
google.maps.event.addListener(marker, 'click', (function(marker, infoWindowContent) {
return function() {
infoWindow.setContent(infoWindowContent);
infoWindow.open(map, marker);
}
})(marker, infoWindowContent));

Related

Multiple markers are not properly showing in google map php

In my laravel project am trying to show locations of my clinics in google maps (Taking lattitude and longitude values from php database). Follwoing is my code in controller.
public function showClinicLocations($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
return view('clinic.locations')->with(['locations' => $locations ,'clinic'=>$clinic]);
}
In view page am properly getting locations .When i consoled the locations.length am getting the result as 12 , its correct and also am getting complete locations name.
But when i tried to show it in marker only 11 locations are showing in google map marker. Following is the code in google map marker.
<script>
// var services =<?php echo json_encode($services);?>;
// console.log(services);
function initMap() {
var locations = <?php echo $locations ?>;
console.log(locations.length);
var j;
for (j = 0; j < locations.length; j++) {
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 8,
center: {
lat: parseFloat(locations[j]['locationLat']),
lng:parseFloat(locations[j]['locationLong'])
}
}
);
setMarkers(map);
}
}
function setMarkers(map) {
var locations = <?php echo $locations ?>;
//var services = <?php echo $services ?>;
//console.log(services);
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: {lat: parseFloat(locations[i]['locationLat']), lng:parseFloat(locations[i]['locationLong'])},
map: map,
title: locations[i]['locationName']
});
var infowindow = new google.maps.InfoWindow()
var content = locations[i]['locationName'];
google.maps.event.addListener(marker,'click',
(function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker, content,infowindow));
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
What is the problem with the code of google maps to show markers
You wanna generate the map only once and maybe also fit the map to the bounds of all displayed markers:
var locations = JSON.parse("<?php echo $locations ?>");
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: {
lat: parseFloat(locations[0]["locationLat"]),
lng: parseFloat(locations[0]["locationLong"])
}
});
setMarkers(map);
}
function setMarkers(_map) {
var boundsToFit = new google.maps.LatLngBounds();
for (var i = 0; i <= locations.length; i++) {
var marker = new google.maps.Marker({
map: _map,
position: {
lat: parseFloat(locations[i]["locationLat"]),
lng: parseFloat(locations[i]["locationLong"])
},
map: _map,
title: locations[i]["locationName"]
});
var infowindow = new google.maps.InfoWindow();
var content = locations[i]["locationName"];
google.maps.event.addListener(
marker,
"click",
(function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(_map, marker);
};
})(marker, content, infowindow)
);
boundsToFit.extend(marker.getPosition());
}
_map.fitBounds(boundsToFit);
}

Google maps individual marker infowindow - how to?

I have this working multy markers script. Markers are printed on the map but when I click on any marker I can see same info window.. Something wrong in this loop:
function bindInfoWindow(marker, map, infowindow, content) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
function initialize() {
var map;
var locations = <?php echo json_encode($location); ?>;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Multiple Markers
var markers = locations;
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ){
loc_array = markers[i].split(",");
var position = new google.maps.LatLng(loc_array[1], loc_array[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
draggable: false,
raiseOnDrag: true,
title: loc_array[0]
});
// Info Window Content
content=loc_array[0] + " - <a class='ac' onclick='move("+ loc_array[4] +");' href='#'>" + <?php echo json_encode($lang['view_profile']);?> + "</a><span class='p'>" + <?php echo json_encode($lang['phone']);?> + ": " + loc_array[6] + " </span><span class='p'>" + <?php echo json_encode($lang['address']);?> + ": " + loc_array[5] + ", " + loc_array[7] + ", " + loc_array[8] + "</span>";
bindInfoWindow(marker, map, infoWindow, content);
//infowindow = new google.maps.InfoWindow();
console.log(content);
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
bounds.extend(marker.position);
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
map.fitBounds(bounds);
google.maps.event.removeListener(boundsListener);
});
}
When I print individual info in console I can see different info windows, but on the map all come same:
console.log(content);
I call initialize() on body load
Please help where I am wrong, Thanks !
First of all declare infowindow globally in following way:
var infoWindow = new google.maps.InfoWindow();
Then after creating marker and content string just call this function:
bindInfoWindow(marker, map, infoWindow, content);
This is the definition of function bindInfoWindow()
function bindInfoWindow(marker, map, infowindow, content) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}

Place multiple php vars as lat/long in Google Maps

This is what I have... PHP pulls down 10 pairs of lat/long from an API url which I have managed to get working okay but I cannot seem to plot them on a map with multiple markers labelled 1-10.
My php code:
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;
//Displaying latitude and longutude
$house = json_encode($house);
}; ?>
JavaScript bit:
var locations = "<?php foreach($xml_search->property as $house) { echo $lat = $house->address->latitude , $long = $house->address->longitude;}; ?>";
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(37.0625,-95.677068),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
Which is then needs to be displayed in here
<div id="map" style="width: 500px; height: 400px"></div>
But I just get a blank page, of course.
Okay, I've managed to figure it out.
Here is my php code in the head part
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;?>
Then I have my javascript
// Load property ID followed by Lat and Long for each house (total of 10)
var locations = [<?php foreach($xml_search->property as $house) {
echo '['.$house->id. ',' .$house->address->latitude. ',' .$house->address->longitude.'],';
} ?>];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function AutoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
// Fit these bounds to the map
map.fitBounds(bounds);
}
AutoCenter();
Works beautifully, now just need to set up labelled markers and I am good to go.

Google Map API - infowindow in foreach loop

Hello I'm retrieving data from SqlServerCe so I created foreach loop to create markers - that works it creates multiple markers but now I wanted to add to each of these marker an infowindow. But now whenever I click on marker the infowindow pops-up on the lastly created marker.
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
, mapProp);
$(function () {
#foreach (var row in data)
{
<text>
var marker = new google.maps.Marker({ position: new google.maps.LatLng(#row.GeoLat, #row.GeoLong),
map: map });
marker.info = new google.maps.InfoWindow({
content: "test"
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
</text>
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
May someone help me with adding infowindow to each created markers?
Thank you for your responding and your time.
This is how I load from SqlServerCe
var db = Database.Open("StarterSite");
var data = db.Query("SELECT DescriptionService,GeoLong,GeoLat FROM services");
var array = new []{data} ;
You can use the following, written in javascript
var infoWindowContent = [];
for(var index=0; index< places.length; index++){
infoWindowContent[index] = getInfoWindowDetails(places[index]);
var location = new google.maps.LatLng(places[index].latitude,places[index].longitude);
bounds.extend(location);
marker = new google.maps.Marker({
position : location,
map : map,
title : places[index].title
});
google.maps.event.addListener(marker, 'click', (function(marker,index){
return function(){
infoWindow.setContent(infoWindowContent[index]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
map.setZoom(15);
}
})(marker,index));
}
function getInfoWindowDetails(location){
var contentString = '<div id="content" style="width:270px;height:100px">' +
'<h3 id="firstHeading" class="firstHeading">' + location.title + '</h3>'+
'<div id="bodyContent">'+
'<div style="float:left;width:100%">'+ location.address + '</div>'+
'</div>'+
'</div>';
return contentString;
}
I added an array infoWindowContent then added the information to the array. You can use the same logic

Every infowindow is displaying the same data maps api v3

I am really stuck on something. Every map marker's infowindow is displaying the same info. It seems to be the content at the end of an array that i use to store content nodes every time. I am pretty sure it is because the infowindow is not being attached to the proper marker
var markers = [];
var contentArray = [];
var titleArray = [];
var latlngArray = [];
var map;
//var infowindow;
var concert;
function defaultMap()
{
//Latitude: 38
//Longitude: -97
//window.alert("inside function");
var mapOptions = {
center:new google.maps.LatLng(38,-97),
zoom:4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
// window.alert("addMarkers the size of contentArray is: "+contentArray.length);
//window.alert("addMarkers the size of the titleArray is: "+titleArray.length);
// window.alert("addMarkers the size of the latLongArray is: "+latlngArray.length);
//for(var i =0;i<2;i++)
//{
// if(i == 0)
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172784,-96.8909115),
// map:map
// });
// markers.push(marker);
// }
// else
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172973,-96.8766355),
// map:map
// });
// markers.push(marker);
// }
// //markers[0] = new google.maps.LatLng(37.8172784,-96.8909115);
// //markers[1] = new google.maps.LatLng(37.8172973,-96.8766355);
//
//}
//addMarkers();
}
//function
//
//{
//infowindow = new google.maps.InfoWindow({
//content:list
//});
//google.maps.event.addListener(marker,'click',function(){
// infowindow.open(map,marker);
//});
function addMarkers()
{
//console.dir(contentArray[contentArray.length-1]);
for(var i = 0;i <10;i++)
{
if(i == 0)
{
//window.alert("i = "+i);
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/club.png',
title:titleArray[i],
map:map
});
//marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker,'click',function()
{
//console.log(infowindow.getContent());
infowindow.setContent(contentArray[i]);
infowindow.open(map,this);
});
markers.push(marker);
}
else
{
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/restaurant.png',
title:titleArray[i],
map:map
});
var infowindow = new google.maps.InfoWindow({});
//console.log(infowindow.getContent());
google.maps.event.addListener(marker,'click',function()
{
infowindow.setContent(contentArray[i]);
console.log(infowindow.getContent());
infowindow.open(map,this);
});
markers.push(marker);
}
//console.log(i);
//console.log(contentArray[i]);
}
}
The problem is that when the loop ends, i is 10.
Every infowindow displays:
infowindow.setContent(contentArray[i]);
There are two ways to solve the problem:
function closure. Use a createMarker function to associate the infowindow content with the marker. Explained in Mike Williams' v2 tutorial, one of his examples using function closure, translated to v3.
marker member variable containing the content, access it in the click listener by referencing "this". The answer to this similar question may help with this. Here is an example of using a member variable of the marker
This Code is also for all those who want to put multiple Markers on Map retrieved from DB
i am going to paste a Code of live project means working. you can get some help from this.
function latLongCallback(latitutde,longitutde){
var latlng = new google.maps.LatLng(latitutde, longitutde);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: 'https://www.xyz.com/yourrfolder/markers.php',
success: function(response){
var total=response.length;
var data_array,name,type,address,lat,lon,arrival,departure,notes;
var infowindow = new google.maps.InfoWindow();
for(var i=0; i < total; i++){
data_array=response[i];
name=data_array['name'];
id = data_array['id'];
address=data_array['address'];
arrival=data_array['arrival'];
departure=data_array['departure'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
icon=data_array['icon'];
sc_id=data_array['sc_id'];
var propPos = new google.maps.LatLng(lat,lon);
propMarker = new google.maps.Marker({
position: propPos,
map: map,
icon: icon,
zIndex: 3
});
var contentString = "<div style='font-size:9px;overflow:hidden'>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Arrival :</label> "+arrival+"<br/><label class='label'>Departure :</label> "+departure+"<br/><label class='label'>Notes :</label> "+notes + "</div><div style='font-size:9px;overflow:hidden'><a href='#2' onclick="+xx+" class='popup-txt' style='font-size:11px; margin-top:3px;'>Message him</a><a href='#1' onclick="+invite+" class='popup-txt' style='font-size:11px; margin-top:3px; float:right;'>Invite Friend</a></div>";
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
bindInfoWindow(propMarker, map, infowindow, contentString);
}
}
});
return;
}
and here is the marker.php mentioned in above js
<?php
$data=array();
$retrive_marker_query = "your query";
$result = db_execute($retrive_marker_query);
$cnt=0;
while ($row = mysql_fetch_assoc($result)){
$name = $row['name'];
$id = $row['fb_id'];
$sc_id = $row['id'];
$address = $row['location'];
$lat = $row['lat'];
$lon = $row['lon'];
$data[$cnt]['name'] = $name;
$data[$cnt]['id'] = $id;
$data[$cnt]['sc_id'] = $sc_id;
$data[$cnt]['address'] = $address;
$data[$cnt]['lat'] = $lat;
$data[$cnt]['lon'] = $lon;
$cnt++;
}
$data=json_encode($data);
echo($data);
<?

Categories

Resources