The code below opens a popup-window whenever a marker on the map is clicked. It works:
<script type="text/javascript">
function popup() {
newwindow = window.open('test.php','Test','width=800,height=500');
newwindow.focus();
return false;
}
function addMarker(lat, lng, map){
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
popup();
});
}
function initialize() {
var myOptions = {
center: new google.maps.LatLng(47.367633, 8.542557),
zoom: 5,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControlOptions:{
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControlOptions:{
style: google.maps.NavigationControlStyle.SMALL
}
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var jsonData = <?php echo $json; ?>;
for(var i = 0; i < jsonData.length; i += 1){
addMarker(jsonData[i].lat, jsonData[i].lng, map);
}
}
</script>
If I add a marker icon, however, the popup-window still opens, but it immediately disappears in the background, i.e., behind the browser window that contains the map:
function addMarker(lat, lng, map){
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
icon: 'myicon.png',
map: map
});
google.maps.event.addListener(marker, 'click', function() {
popup();
});
}
What is the reason for this behavior?
This is an interesting issue. It looks like it has to do with the Google Map window requesting focus after the click event. It's strange how it only happens when you use a custom marker icon though.
You could consider working around this issue by launching your popup with a slight delay of 1 millisecond. Tested on Firefox 3.6.3 and it seems to solve your problem:
function popup() {
setTimeout(function () {
var newwindow = window.open('test.php','Test','width=800,height=500');
newwindow.focus();
}, 1);
return false;
}
However, you could also consider not using popup windows at all. Many users still consider them evil, and you'd probably end up battling with popup blockers all the time.
Related
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 created a custom map with most things I want on it (custom icon and custom info bubble), however I can't find a solution to automatically open the markers info window on load, I've done alot of searching but can't seem to find anything the code I have so far is as follows, any help would be much appreciated:
function initialize() {
var myLatlng = new google.maps.LatLng(54.325109,-2.742226);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{
title:'Remedy',
lat:54.3210,
lon:-2.7438,
content:"<h2>Remedy</h2><p>address, <br />location, <br />postcode</p> <p><b>T:</b> 07595 153 835 <br /><b>E:</b> <a href='mailto:email'>email</a></p>"
}
];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
icon: '/wp-content/themes/remedy/display_images/google_map_icon.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
infowindow.open(map, marker);
}
Maybe it's not working because you just created the instance of the Map and didn't wait for the complete load of the map to open the InfoWindow.
Try something like this:
google.maps.event.addListenerOnce(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
According to the reference:
http://code.google.com/intl/en/apis/maps/documentation/javascript/reference.html#Map
tilesloaded - This event is fired when the visible tiles have finished loading.
Hmm, inforwindow does not refer to anything in your code, which is why it is not working.
Since you have one country in the list as of now you can do a quick test and intialize the infowindow variable with an actual info window, or better yet also since you have 1 item in the list, just define c to be outside the loop so you can access it and then open the popup passing it the map and the marker, something like this (assuming c has been defined outside the loop)
c.infowindow.open(map, c.marker);
var infowindow = new google.maps.InfoWindow({
content: "Test Route",
position: new google.maps.LatLng(38.8709866, -77.208055),
});
infowindow.open(map);
I currently have an array of places for a custom map that I am working on. I have been trying but cannot figure out how to add the 'click' popup box over a marker. I want the white box to display the name and have an option so that a person can choose 'get directions to here'. Does anyone know how I can achieve this with more then one marker?
<!DOCTYPE html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 50% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
var map;
var marker
function initialize() {
var latlng = new google.maps.LatLng(42.098687,-75.917974);
var restaurants = new Array();
restaurants = [
new google.maps.LatLng(42.898687,-75.917974),
new google.maps.LatLng(42.698687,-73.917974),
new google.maps.LatLng(42.198687,-75.917974),
new google.maps.LatLng(41.098687,-75.917974)
];
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var i = 0;
for ( i <0; i < restaurants.length;i++ ){
var marker = new google.maps.Marker({
position: restaurants[i],
map:map,
title:"Testing!"
});
popupDirections(marker);
}
}
function popupDirections(marker) {
var infowindow = new google.maps.InfoWindow(
{ content: "tests: "
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:50%; height:50%"></div>
</body>
</html>
The pop-up box that you are talking about is called the info window in google map language.
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("your contents");
});
The above code binds a click event with your marker and opens an info window with the specified text. here marker is the marker object.
Hope it helps.
The way to do this is to create one global infowindow and then reuse it again and again, this way the infowindow is just moved to each marker, and the content of the info window can be changed using the setContent method. Read here and there is a Google Demo accessable from the api reference site. I had the same problem when I was making a map for my site,
The following code should work:
<script type="text/javascript">
var map;
var marker;
var infowindow; //Global infowindow created
function initialize() {
var latlng = new google.maps.LatLng(42.098687,-75.917974);
var restaurants = new Array();
restaurants = [
new google.maps.LatLng(42.898687,-75.917974),
new google.maps.LatLng(42.698687,-73.917974),
new google.maps.LatLng(42.198687,-75.917974),
new google.maps.LatLng(41.098687,-75.917974)
];
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({ //infowindow options set
maxWidth: 355
});
var i = 0;
for ( i <0; i < restaurants.length;i++ ){
marker = new google.maps.Marker({
position: restaurants[i],
map:map,
title:"Testing!"
});
popupDirections(marker);
}
}
function popupDirections(marker) {
//this function created listener listens for click on a marker
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("Tests: "); //sets the content of your global infowindow to string "Tests: "
infowindow.open(map,marker); //then opens the infowindow at the marker
});
}
</script>
If you want separate content for each marker (which I assume you will) you can pass some content into the popupDirections() function, modified with a string for the content "html":
function popupDirections(marker, html) {
//this function created listener listens for click on a marker
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html); //sets the content of your global infowindow to string "Tests: "
infowindow.open(map,marker); //then opens the infowindow at the marker
});
}
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);
};
}