I'm using the following code to generate marker pins. It loads perfectly, but to the left of this map I have filters. How do I reload the markers without reloading the map? This has been causing some frustration so any help would be appreciated.
Many thanks,
//Google map results
var contentStrings = [];
var infowindow = new google.maps.InfoWindow();
var mapinited = false;
var map;
var myOptions = {
zoom: 11,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var currentinfobox;
var myLatlng;
var markersArray=[];
var LatLngList = [];
$().ready(function() {
//reinit search
if (window.location.hash) {
submitForm(window.location.hash.replace('#',''));
}
else if (readCookie('sf')) {
//submitForm(readCookie('sf'));
}
//init map
$('#map_view').click(function() {
if (mapinited) {
return;
} else {
mapinited = true;
initMap();
}
function initMap() {
locate(["Ireland"],function(result) {
map = new google.maps.Map(document.getElementById("search_map"), myOptions);
myLatlng = new google.maps.LatLng(result.lat(),result.lng());
var key =0;
$.each(map_results, function(key, value){
LatLngList[key] = new google.maps.LatLng(value.lat,value.long)
contentStrings[key] =
'<div id="ginfo_content" class="map-pop-up">'+
'<span class="content-top"> </span>'+
'<div class="content-middle">'+
'<div class="map-filler">'+
'<a class="map-close" href="javascript:;" onclick="infowindow.close();" title="Close">x</a>'+
'<br class="clearfix">'+
'<div class="map-pop-up-left">'+
'<div class="thumbnail"><img src="'+ value.image +'" width="64" height="64"></div>'+
'Contact'+
'</div>'+
'<div class="map-pop-up-right">'+
'<h2>'+ value.firstname +' '+value.lastname+', '+ value.address +'</h2>'+
'<p>'+ stripslashes(value.about) +'</p>'+
'</div>'+
'<br class="clearfix">'+
'<div class="map-pop-up-footer">View Profile<span class="telephone">Telephone: '+ value.phone +'</span></div>'+
'</div>'+
'</div>'+
'<span class="content-bottom"> </span>'+
'</div>';
key++;
});//end each
map_results="";
google.maps.event.addListener(infowindow, 'domready', function() {
var infocontent = $('#ginfo_content').clone();
var l = $('#ginfo_content').parent().parent().parent().addClass('original_popup').html('');
$('.original_popup').append(infocontent).show();
$('.original_popup').css('width','360px').css('height','230px').css('left','+=27px').css('top','+=65px');
});
var zoomChangeBoundsListener = google.maps.event.addListener(map, 'zoom_changed', function() {
if (this.getZoom() > 14) // Change max/min zoom here
this.setZoom(14);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
var infoboxlistener = google.maps.event.addListener(map, 'zoom_changed', `enter code here`function() {
infowindow.close();
});
loadMapInit(LatLngList,contentStrings);
});
}
});
});
Hopefully this is answering what you're asking:
When you create a marker, you can use the 'map' parameter to set its map and have it show up. Or, if you want to tie it to a filter, you can ignore the map paramter and use marker.setMap(map) later.
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
If you want to 'remove' and 'add' markers with events, you can use marker.setMap(null) to remove the marker and marker.setMap(map) to re-add it.
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
// To remove the marker from the map
marker.setMap(null);
https://developers.google.com/maps/documentation/javascript/markers
Update:
So if you wanted to 'reload' the markers, you could traverse through and array of currently active markers, set their maps to null, and then reset them on the map.
My page loads maps in two scenarios 1) first load 2) ongoing refreshing of a google map through ajax calls.
The following worked for me
<input type="hidden" id="lonDeg"><!--route lat to here via ajax call-->
<input type="hidden" id="latDeg"><!--route lon to here via ajax call-->
<script>
var map;
function initMap() {
// these two lines are the only variation from the native google
// API code. They allow for dynamic updates of the lon/lat (below)
var lonDeg = parseFloat($("#lonDeg").val());
var latDeg = parseFloat($("#latDeg").val());
var midp = {lat:latDeg, lng:lonDeg };
map = new google.maps.Map(document.getElementById('map'), {
scaleControl: true,
center: midp,
zoom: 10
});
var marker = new google.maps.Marker({map: map, position: midp});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
The event trigger in my case a button
<button id="getNextMap">Go to Next Map</button>
Then finally the javascript that makes it all happen
var qstring = 'myArgsToPass';
var csv = new Array();
$.ajax({
url: 'mapProfileGrabber.php',
type: 'POST',
data: {q:qstring},
success: function(data) {
csv = data.split(",");
$("#lonDeg").val(csv[0]);
$("#latDeg").val(csv[1]);
initMap();
}
In my case, I'm using SVG icons, and I'm changing the strokeColor in code, after the marker (and its icon) are on the map.
To have the map display the new color, I simply call setMap again:
marker.setMap(map);
I find no need to remove it first with marker.setMap(null);
I have a hunch this will work with other changes to the marker, like its icon's URL, etc.
Related
In my website, when I'm doing the design the google map was worked. After the hosting it shows an error:
Oops! Something went wrong"
I tried to find the solution and found API key is missing. I had created a key with my personal Gmail account and added to footer place like below.
<script async defer src="https://maps.googleapis.com/maps/api/js?key=my api key=google-map" type="text/javascript"></script>
But after that also it didn't work. below is my google map script in HTML and js.
//Google Map
var latitude = $('#google-map').data('latitude')
var longitude = $('#google-map').data('longitude')
function initialize_map() {
var myLatlng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 14,
scrollwheel: false,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
var contentString = '';
var infowindow = new google.maps.InfoWindow({
content: '<div class="map-content"><ul class="address">' + $('.address').html() + '</ul></div>'
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize_map);
});
<div id="google-map" class="wow fadeIn" data-latitude="13.0938666" data-longitude="80.202357" data-wow-duration="1000ms" data-wow-delay="400ms"></div>
I have a simple Google Maps feat I'm trying and failing to accomplish.
Presently, I can display my map, then cycle through a list of Projects via PHP (I'm using ExpressionEngine), and add each project's latitude/longitude to a JavaScript array.
Once the values are in the JavaScript array, I use jQuery to cycle through each one, and add a marker to the map.
I'm able to click the map and have it respond appropriately; however, when I attempt to click one of the markers, nothing happens at all.
I have tried moving code, renaming, changing, editing, and tweaking endlessly... I cannot figure this out. Any help at all would be hugely appreciated. My code is as follows:
<script>
// Create the new map_locations array
var map_locations = [];
</script>
<!-- The following ExpressionEngine script loops through all the 'projects' on the site,
then pushes each project to the map_locations array. -->
{exp:channel:entries channel="projects"}
<script>
map_locations.push( ['{url_title}', '{project_latitude}', '{project_longitude}', '{categories}{category_name}{/categories}', '{title}'] );
</script>
{/exp:channel:entries}
<script>
var marker;
function initialize() {
// To add the marker to the map, use the 'map' property
var mapOptions = {
center: { lat: 51.884 , lng: -95.147 },
zoom: 4
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a new location lat/long var, newLatLng
var newLatLng;
var contentString = "<div id='info_window'>this is the info window</div>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var iconBase = '/images/map_icon_';
$.each( map_locations, function()
{
newLatLng = new google.maps.LatLng( this[1] , this[2] );
marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
});
google.maps.event.addListener(marker, 'click', function() {
console.log( "This marker's url_title is: " + this[0] );
});
google.maps.event.addListener(map, 'click', function() {
console.log( "Testing map click" );
});
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You are trying to add event listener for markers after the loop where marker gets defined rather than in the loop
Try:
$.each( map_locations, function(){
var newLatLng = new google.maps.LatLng( this[1] , this[2] );
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
google.maps.event.addListener(marker, 'click', function(marker) {
console.log( "This marker's url_title is: " + marker.title );
});
});
I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
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]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.
As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/
UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
I've seen the other posts, but they dont have the markers being looped through dynamically like mine. How do I create an event that will close the infowindow when another marker is clicked on using the following code?
$(function(){
var latlng = new google.maps.LatLng(45.522015,-122.683811);
var settings = {
zoom: 10,
center: latlng,
disableDefaultUI:false,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
$.getJSON('api',function(json){
for (var property in json) {
if (json.hasOwnProperty(property)) {
var json_data = json[property];
var the_marker = new google.maps.Marker({
title:json_data.item.headline,
map:map,
clickable:true,
position:new google.maps.LatLng(
parseFloat(json_data.item.geoarray[0].latitude),
parseFloat(json_data.item.geoarray[0].longitude)
)
});
function buildHandler(map, marker, content) {
return function() {
var infowindow = new google.maps.InfoWindow({
content: '<div class="marker"><h1>'+content.headline+'</h1><p>'+content.full_content+'</p></div>'
});
infowindow.open(map, marker);
};
}
new google.maps.event.addListener(the_marker, 'click',buildHandler(map, the_marker, {'headline':json_data.item.headline,'full_content':json_data.item.full_content}));
}
}
});
});
I finally figured it out... no thanks to anyone here... It was actually fairly easy:
First, set up some vars to store the infowindow:
var infowindow;
Then add this to wherever your onClick function is that triggers the other infowindow.open(). Put it above the open though:
if(infowindow) {infowindow.close()}
Inside your loop or however else you are adding markers.
E.g. in full action:
At the very top of my script:
var infowindow;
Inside my loop of adding markers:
function buildHandler(map, marker, content) {
return function() {
if(infowindow) {infowindow.close()}
infowindow = new google.maps.InfoWindow({
content: 'My Content here'
});
infowindow.open(map, marker);
};
}