Google Map API - infowindow in foreach loop - javascript

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

Related

Google Maps API Multiple Marker InfoWindowContent showing same data

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

Google Map, Users Create Markers, How do I save

I've got code to allow users to pin a marker on a map. What I am missing is how to save the markers so that when the map reloads, the markers are still there.
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var myCenter=new google.maps.LatLng(38.9047,-77.0164);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:7,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You could utilize google.maps.Data API for that purpose, the example below demonstrates how to save and load markers info via localStorage.
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
//place marker info
map.data.add(new google.maps.Data.Feature({properties:{},geometry:new google.maps.Data.Point(location)}));
}
function saveMarker() {
map.data.toGeoJson(function (json) {
localStorage.setItem('geoData', JSON.stringify(json));
});
}
function clearMarkers() {
map.data.forEach(function (f) {
map.data.remove(f);
});
}
function loadMarkers(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.addGeoJson(data);
}
Demo

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

My markers wont work on my istamap

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);
var marker = new google.maps.Marker ({
position: (51.508742,-0.120850),
map: map,
animation: google.maps.Animation.BOUNCE
});
$.getJSON("muziek.php", function (data){
$.each(data, function() {
$.each(this, function (key, value) {
if (value.location != undefined){
var myLatlng = new google.maps.LatLng(value.location.latitude, value.location.longitude);
var images = value.images.low_resolution.url;
var infowindow = new google.maps.infowindow({
content:
"<img src='" +images+ "'>"
});
google.map.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
My markers won't put photos on mine google map how can i fix this and put markers with the data from my istagram on mine google maps. I already consolelog my position but i wont get any result back.
I suggest double checking your img sources. The following works fine for me:
var contentString = '<img src="[URL of image]">';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Test',
//animation: google.maps.Animation.BOUNCE
});

Google map Zoomed fully

Hi in my google map i just draw a one marker when map loads.But then map is zoomed fully in which is really confusing. but when i draw more than one markers map is centered properly and zoomed to a certain level. how can it overcome this.
i have got a loop inside my draw markers function and in that i get only one object that has coordinates. when i get more than one objects from 'markers' map is centered properly. but when it has a only one object to loop. markers gets drawn but map is not well centered and zoomed(zoomed in fully)
function drawMarkers(markerList) {
debugger;
var mapOptions = {
center: new google.maps.LatLng(-24.504710, 134.039231),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var currentLocation;
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
//if (markerList[i].Longitude > 0) {
var data = markerList[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.DriverName,
});
var driverCurrentLocation = document.getElementById('<%= hdfDriverCurrentLocation.ClientID %>').value;
latlngbounds.extend(marker.position);
//if (markerList[i].Longitude > 0) {
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
debugger;
var lat = data.Latitude;
var lng = data.Longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
currentLocation = results[1].formatted_address;
}
infoWindow.setContent('<div style="overflow: auto;width: 275px;">' +
'<div id="leftSideMainDiv" class="col25" style="padding-Left:0px; width:22%;">' +
'<div class="col100"><img src="../Images/DriverImages/driver_icon.jpg" height="60" width="60"/></div>' +
'</div>' +
'<div id="RightSideMainDiv" class="col75" style="width:72%;">' +
'<div class="col100" style="font-weight:bold; padding-top:0px; padding-left:0px; font-size:smaller;"> ' + data.DriverName + '</div>' +
'<div style="font-size:smaller; padding-top:15px;">Job Number :' + data.JobId + ' - ' + data.JobType + '</div>' +
'<div style="font-size:smaller;">Delivery Address :' + data.DeliveryAddress + '</div>' +
'<div style="font-size:smaller;">Current Location :' + currentLocation + '</div>' +
'<div style="font-size:smaller;">Last Update :' + data.LastUpdatedTime + '</div>' +
'</div>');
infoWindow.open(map, marker);
}
});
});
})(marker, data);
//}
}
//}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
}
Related question: How to set zoom level in google map
If you only have one marker (markers.length == 1), then don't call map.fitBounds(). Change:
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(5);
To:
map.setCenter(latlngbounds.getCenter());
if (marker.length != 1) map.fitBounds(latlngbounds);
map.setZoom(5);
on the initialization of maps set the zoom level, Here the zoom is set to 5
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
Add the map variable outside of map's function scope
var map;
and then modify the line inside your map function-
map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
then after calling your map function drawMarkers(markerList) you need to set the zoom as-
$(document).ready(function(){
drawMarkers(markerList)
google.maps.event.addDomListener(window, 'load', function () {
map.setZoom(5);
});
});
Let me know if that works!

Categories

Resources