Unable to add url to google maps click event - javascript

I'm stuck on this problem, no matter what I have tried, I cannot add a url to the google maps marker.
Can anyone with more experience than me please help with this problem.
Currently, if I click the marker, I'm taking back to the home page, what I want is to go to this url '/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId'which is in the foreach loop.
I have looked at
google map api: open url by clicking at marker
Google Map marker url
and other but i'm stuck
My code is:
<script type="text/javascript">
$(function() {
var map;
var markersArray = [];
var image = 'img/';
var bounds = new window.google.maps.LatLngBounds();
var loc;
//var pageUrl;
var mapOptions = { mapTypeId: window.google.maps.MapTypeId.ROADMAP };
map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
#foreach (var item in Model.DisplayHotelPaging)
{
<text> loc = new google.maps.LatLng(#item.Latitude, #item.Longitude);
bounds.extend(loc);
addMarker(loc, '#item.DisplayHotelName #item.Address1 #item.PostalCode', "active",'/Hotel/Full-Details?=#item.DisplayHotelName&propId=#item.HotelId')
</text>
}
map.fitBounds(bounds);
map.panToBounds(bounds);
//for (var i = 0; i < window.addMarker.length; i++) {
function addMarker(location, name, active) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: '/'//page[3]
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
});
</script>
Thanks for any help

I believe you need to add the URL to your addMarker function like so:
function addMarker(location, name, active, markerUrl) {
//var page = loc[i];
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active,
icon: '/Images/property1.png',
url: markerUrl
});
// }
window.google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
}
Currently you hard-coded '/' as your URL which would take you to your home page.

Related

Marker event.listener iteration issue, Laravel

What I am trying to do here. When I press the marker. It should send me to the that id's page. It sending me to id's page. But it doesn't matter which marker I click I always going to same id's page. Listener is not working properly... I guess...
This is the full map:
var estates = <?php echo json_encode($estates);?>;
function initMap()
{
var options =
{
zoom : 6,
center : {lat:34.652500, lng:135.506302}
};
var map = new google.maps.Map(document.getElementById('map'), options);
#foreach ($estates as $est)
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/{{$est->id}}",
label: {
text: estates.data[0].price.substring(0, 5),
color: "#fff",
},
position: {
lat: {{$est->lat}},
lng: {{$est->lng}}
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = marker.url;
});
#endforeach
}
Any idea to fix this problem?
Please try:
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
It seems like that window.location.href = marker.url; lack of [i] of marker

Refresh primefaces gmap markers in javascript

I need to refresh, add new markers or remove markers on a primefaces gmap.
By a callBackParam I pass the markers to a javascript in xhtml.
However when the map refreshes, the event overlaySelect is never fired.
ManageBean scope is viewScoped
public void ajaxPoll() {
Marker[] newMarkers = new Marker[mapLoadModel.getMarkers().size()];
for(int i=0;i < newMarkers.length;i++){
newMarkers[i]=mapLoadModel.getMarkers().get(i);
}
RequestContext.getCurrentInstance().addCallbackParam("newMarkers",new Gson().toJson(newMarkers));
logger.info("refresco marcadores");
}
The javascript:
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
for(var i in gmap.markers)
{
gmap.markers[i].setMap(null);
}
gmap.markers.length=0;
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in newMarkers)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
id: newMarker.id,
map: gmap,
position: newMarker.latlng,
icon:newMarker.icon,
title:newMarker.title,
clickable:true
});
}
}
// ]]>
And the map:
<p:poll interval="#{manageLoadExecution.refreshInterval}" listener="#{manageLoadExecution.ajaxPoll}" oncomplete="handleComplete(xhr, status, args)" process="#this" />
<p:gmap widgetVar="gMapWV" id="gMapWV" center="#{manageLoadExecution.latitude} , #{manageLoadExecution.longitude}" zoom="#{manageLoadExecution.zoomLevel}" fitBounds="false" type="terrain" model="#{manageLoadExecution.mapLoadModel}" disableDefaultUI="false" styleClass="map" >
<p:ajax event="overlaySelect" listener="#{manageLoadExecution.onMarkerSelect}" />
<p:gmapInfoWindow id="infoWindow" maxWidth="400" >
<p:outputPanel style="text-align: left; display: block; margin: auto; width:370px" >
After refresh the markers are show on screen, but the overlaySelect event is never fired and the infowindow is not open.
I guess that removing all the markers I'm removing some that makes the event not fires.
Please, any help!
Thank you very very much.
I made it!
I missed to add an id the the new marker in javascript scriptlet.
Finally in javascript code I call _render() method to configure markers and listeners.
Here is the javascript scriptlet:
<script>
//<![CDATA[
function handleComplete(xhr, status, args){
var gmap = PF('gMapWV').getMap();
var newMarkers = eval('(' + args.newMarkers + ')');
for(var i in gmap.markers)
{
var oldMarker = gmap.markers[i];
var newMarker = newMarkers[i];
if(newMarker != null){
oldMarker.setPosition(newMarker.latlng);
oldMarker.title=newMarker.title;
oldMarker.setMap(gmap);
oldMarker.id=newMarker.id;
}else{
oldMarker.setMap(null);
}
}
var oldMarkersLength = gmap.markers.length;
var newMarkersLength = newMarkers.length;
for(var i = oldMarkersLength;i < newMarkersLength;i++)
{
var newMarker = newMarkers[i];
var marker = new google.maps.Marker({
position: newMarker.latlng,
title:newMarker.title,
clickable:true,
id:newMarker.id
});
gmap.markers[i]= marker;
}
PF('gMapWV').addOverlays(gmap.markers);
PF('gMapWV')._render();
}
// ]]>
</script>
If the list decrease the size I set the remain markers to null to reuse then if I need it.
I hope this can help anyone stuck with gmap and primefaces.
Thanks everyone for suggestions
Try to do this, it work to me (for those don't want refresh the map):
var gmap = PF('gmap').getMap();
var marker = new google.maps.Marker({
id: json.id,
map: gmap,
position: json.latlng,
icon: json.icon,
title: json.title,
draggable: true,
clickable:true
});
gmap.markers[gmap.markers.length] = marker;
PF('gmap').addOverlay(marker);
PF('gmap').configureMarkers();
PF('gmap').addOverlays(gmap.markers);

Remove marker from Google Maps API V3

I have a map where I want to add a marker (with info window) via a checkbox. It also works quite well, but I just can not get it deleted again when I uncheck the checkbox. Can anyone help?
See also here: http://jsfiddle.net/x8D7y/
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
}
function showOverlays() {
var marker300 = new google.maps.Marker({
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
});
var infowindow300 = new google.maps.InfoWindow({
content: '<div style="width: 200px;">Test 300 - Link</div>'
});
google.maps.event.addListener(marker300, 'click', function() {
infowindow300.open(map, marker300);
});
}
You have to use an external Array which holds the extra markers you use with the map. In your case I have added the following array:
var extraMarkers = [];
Then when I click the checkbox, I am getting the ID of that checkbox, and send it in both showOverlays() and clearOverlays() as function argument.
Then, in showOverlays(), I am using the checkbox ID as extraMarkers key and the marker as value.
Finally, in clearOverlays() I use again the checkbox ID to get the element with this ID from the extraMarkers array and I see the map to null, in order to remove the marker.
See here the working example : http://jsfiddle.net/x8D7y/1/
Here is the full code required by you:
var map;
var extraMarkers = [];
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(45.0, 1.0)
};
map = new google.maps.Map($('#map')[0], myOptions);
var marker1 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.5, 1.5),
map: map /*,
icon: 'img/bike5.png' */
}
);
var infowindow1 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 1 - Link</div>'
}
);
google.maps.event.addListener(
marker1,
'click',
function()
{
infowindow1.open(map, marker1);
}
);
function clearOverlays(myID)
{
google.maps.event.clearListeners(extraMarkers[myID], 'click');
extraMarkers[myID].setMap(null);
}
function showOverlays(myID)
{
var marker300 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
}
);
extraMarkers[myID] = marker300;
var infowindow300 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 300 - Link</div>'
}
);
google.maps.event.addListener(
marker300,
'click',
function()
{
infowindow300.open(map, marker300);
}
);
}
$('#mapall').change(
function()
{
var myID = $(this).attr('id');
if($('#mapall').attr('checked'))
{
showOverlays(myID);
}
else
{
clearOverlays(myID);
}
}
);
if you have single marker on map then use marker.setMap(null);
if Multiple marker make an array for marker
markersArray.push(marker);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
Try this:
marker300.setMap(null);
Your marker was not visible outside of showOverlays() function. Error was reported in console:
Uncaught ReferenceError: marker300 is not defined
Minimum change is to define marker300 as global:
var map;
var marker300;
and delete marker in
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
marker300.setMap(null);
}
and remove var in front of variable marker300 in function showOverlays()
See example in fiddle
If you want to have several markers than you will have to follow solution from user Merianos Nikos

Google Places API, additional marker (manually added) to results

My javascript isn't too hot, I'm trying to add a manual marker onto a number of locations gathered from the Google Places API.
I followed this post to get to my following code (with a few amendments):
<script type="text/javascript">
var map;
var infowindow;
var service ;
base_Icon_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.png";
shadow_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.shadow.png";
function initialize(lat,lng)
{
var origin = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.HYBRID,
center: origin,
zoom: 14,
scrollwheel: false,
});
var request = {
location: origin,
radius: 2500,
types: ['train_station','bus_station','subway_station','airport']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
base_Icon_train = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
base_Icon_bus = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
base_Icon_subway = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
base_Icon_airport = "http://maps.google.com/mapfiles/ms/icons/yellow.png";
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker;
var icon_to_use;
if (place.types.indexOf('train_station') != -1) {
icon_to_use = base_Icon_train;
} else if (place.types.indexOf('bus_station') != -1) {
icon_to_use = base_Icon_bus;
} else if (place.types.indexOf('subway_station') != -1) {
icon_to_use = base_Icon_subway;
} else if (place.types.indexOf('airport') != -1) {
icon_to_use = base_Icon_airport;
}
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
var content='<strong style="font-size:1.2em">'+place.name+'</strong>'+
'<br/><strong>Latitude: </strong>'+placeLoc.lat()+
'<br/><strong>Longitude: </strong>'+placeLoc.lng()+
'<br/><strong>Type: </strong>'+place.types[0];
//make a request for further details
service.getDetails({reference:place.reference}, function (place, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
more_content='<hr/><strong>Details';
if(place.website)
{
more_content+='<br/><br/><strong>'+place.website+'';
}
}
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content+more_content);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', function(){initialize(<?php echo $coordinated; ?>);});
</script>
<div id="map" style="height:400px;"></div>
Now I would like to manually add another marker which is located at the center of the map (ie, the variable origin which is currently being pulled from a PHP variable - var origin = new google.maps.LatLng(lat,lng);). I also need this marker to have a different icon associated with it (base_Icon_festival and shadow_festival respectively).
I'm not sure how to manually add another marker to the ones already gathered by the places API?
End goal: have a festival icon marker at the center of the map and a number of public transport markers surrounding it, resulting code to go on individual festival pages of a website.
Thanks in advance to anyone who can help.
In the Google Maps API, markers are added to the map by creating a Marker object and setting the map property. This is the snippet in your code that adds the existing Markers.
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
To add a new marker you would just replace the position and icon properties with your values.
new google.maps.Marker({
map: map,
position: origin,
icon: shadow_festival
});
This code can probably be added at the end of the Callback function and if you don't need the actual marker object for anything else, you can just create the Marker object and never assign it.
There is an example from the Google Maps API docs here.

"a is null" even after Google map is successfully loaded

I have a set of jQuery UI tabs that each load project.php using ajax. Depending on the parameters passed to the script, a different Google map is displayed using the following JavaScript inside project.php:
var tab_index = $('#tabs').tabs('option', 'selected');
$('.site_map:visible').css('height','300px');
MapID = $('.site_map:visible').attr('id');
if (MapID !== 'map-new'){
var map_id = 'map-'+tab_index;
$('.site_map:visible').attr('id', map_id);
} else {
MapNewSite();
}
var latlng = new google.maps.LatLng(19,-70.4);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-" + tab_index), myOptions);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
placeMarker($('.site_details:visible .inpLat').val(), $('.site_details:visible .inpLng').val(), tab_index);
function MapNewSite(){
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-new"), myOptions);
placeMarker(19,-70.4,tab_index);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
}
Each map loaded using parameters returned by a query of my database loads without any problems. However, in one last instance, I load project.php in a tab without any parameters so as to have a blank tab for users to manipulate. The signal that the map is not to be loaded using database coordinates is that the id of its div is "map-new".
The map generated in this tab loads, but then gives me the "a is null" error which usually means it couldn't find a div with the id specified to initialize the map. What is causing this error even after the map has loaded? How do I stop the error from occurring?
Here is the JavaScript in the parent page containing the tab site:
var arrMaps = {};
var arrInfoWindows = {};
var arrMarkers = {};
function placeMarker(lat, lng, tab_index){
map = arrMaps[tab_index];
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
bounds.extend(latlng);
createMarker(latlng, tab_index);
map.fitBounds(bounds);
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(10);
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
}
function createMarker(latlng, tab_index) {
var html = 'Click here to move marker';
arrMarkers[tab_index] = new google.maps.Marker({
map: arrMaps[tab_index],
position: latlng
});
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
google.maps.event.addListener(arrMarkers[tab_index], 'click', function() {
arrInfoWindows[tab_index].setContent(html);
arrInfoWindows[tab_index].open(arrMaps[tab_index], arrMarkers[tab_index]);
});
}
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
},
cache: true
});
});
Take a look to http://www.pittss.lv/jquery/gomap/. Easy to use and very powerful. I myself use it.
It turns out I was accidentally initializing the map both inside the if and outside of it.

Categories