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
Related
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);
});
}
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
});
I'm having trouble getting the Google Maps MarkerClusterer to work. I'm fairly sure I follow procedure correctly (i.e. creating the map, adding markers to an array, not setting the markers to a map, and then attaching the map and the markers to a MarkerClusterer), which leads me to believe maybe it has to do something with Google Maps v3 versus v2. I'm just creating markers from a json file and than filtering the markers based off of user input.
Quick note: When I add a map to the marker all the markers show up, but they just aren't clustered.
$('document').ready(function() {
$('#map').height($(window).height() - $('#map').position().top - 20);
var mapElem = document.getElementById('map');
var center = {
lat: 47.6,
lng: -122.3
}
var map = new google.maps.Map(mapElem, {
center: center,
zoom: 12
});
var infoWindow = new google.maps.InfoWindow();
var cameras;
var markers = [];
$.getJSON('http://data.seattle.gov/resource/65fc-btcc.json')
.done(function(data) {
cameras = data;
cameras.forEach(function(cameras) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(cameras.location.latitude),
lng: parseFloat(cameras.location.longitude)
}
});
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
var html = '<p>' + cameras.cameralabel + '</p>';
html += '<img src="' + cameras.imageurl.url + '"/>';
infoWindow.setContent(html);
infoWindow.open(map, this);
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
markers.push(marker);
$('#search').bind('search keyup', function() {
var cameraName = cameras.cameralabel.toLowerCase();
var searchString = this.value.toLowerCase();
if (cameraName.indexOf(searchString) < 0) {
marker.setMap(null);
} else {
marker.setMap(map);
}
});
});
})
.fail(function(err) {
console.log(err);
alert('Sorry, unfortunately something went wrong!');
});
var markerCluster = new MarkerClusterer(map, markers);
$(window).resize(function() {
$('#map').height($(window).height() - $('#map').position().top - 20);
});
});
You need to initialize the MarkerClusterer inside the callback function (where the markers array is created).
$('document').ready(function() {
$('#map').height($(window).height() - $('#map').position().top - 20);
var mapElem = document.getElementById('map');
var center = {
lat: 47.6,
lng: -122.3
}
var map = new google.maps.Map(mapElem, {
center: center,
zoom: 12
});
var infoWindow = new google.maps.InfoWindow();
var cameras;
var markers = [];
$.getJSON('http://data.seattle.gov/resource/65fc-btcc.json')
.done(function(data) {
cameras = data;
cameras.forEach(function(cameras) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(cameras.location.latitude),
lng: parseFloat(cameras.location.longitude)
}
});
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
var html = '<p>' + cameras.cameralabel + '</p>';
html += '<img src="' + cameras.imageurl.url + '"/>';
infoWindow.setContent(html);
infoWindow.open(map, this);
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
markers.push(marker);
$('#search').bind('search keyup', function() {
var cameraName = cameras.cameralabel.toLowerCase();
var searchString = this.value.toLowerCase();
if (cameraName.indexOf(searchString) < 0) {
marker.setMap(null);
} else {
marker.setMap(map);
}
});
});
// here, inside the .done function
var markerCluster = new MarkerClusterer(map, markers);
})
.fail(function(err) {
console.log(err);
alert('Sorry, unfortunately something went wrong!');
});
$(window).resize(function() {
$('#map').height($(window).height() - $('#map').position().top - 20);
});
});
working fiddle
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
I'm having a problem centering my InfoWindow on page load. On load, the map is centering on the marker, which puts the InfoWindow off screen (I'm working with a short height for my map container).
Now clicking the marker does re-center the map on the InfoWindow so that it looks exactly like I want. That being the case, I've even tried firing the marker.click trigger to achieve a solution on load, but had no luck. What am I missing?
JSFIDDLE: http://jsfiddle.net/q9NTS/7/
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
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 = '#(Model.Event.Address)' + ', ' + '#(Model.Event.City)' + ', ' + '#(Model.Event.State)' + ' ' + '#(Model.Event.Zip)';
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: '#(Model.Event.Venue)'
});
map.setCenter(marker.getPosition());
var content = 'blah';
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 {
//
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You apparently just need to wait longer before triggering the click event.
// wait until the map is idle.
google.maps.event.addListenerOnce(map, 'idle', function() {
setTimeout(function() {
// wait some more (...)
google.maps.event.trigger(marker, 'click'); //still doesn't work
},2000);
});
fiddle