I' m using google map api version 3 for this program. What I m trying to do is change the position of infoWindow which appears on mouseover. Currently it shows on the marker. I want to change the position to show it on top of the marker icon. When I replace
speedTest.infoWindow.setPosition(latlng);
speedTest.infoWindow.open(speedTest.map);
These two lines with following line,
speedTest.infoWindow.open(speedTest.map, this);
It shows correctly on top of the marker. but then infoWindow will not able popup when I trigger mouse event from side items.
speedTest.showMarkers = function() {
speedTest.markers = [];
var type = 1;
if ($('usegmm').checked) {
type = 0;
}
if (speedTest.markerClusterer) {
speedTest.markerClusterer.clearMarkers();
}
var panel = $('markerlist');
panel.innerHTML = '';
var numMarkers = $('nummarkers').value;
for (var i = 0; i < numMarkers; i++) {
var titleText = speedTest.pics[i].photo_title;
if (titleText == '') {
titleText = 'No title';
}
var item = document.createElement('DIV');
var title = document.createElement('A');
title.href = '#';
title.className = 'title';
title.innerHTML = titleText;
item.appendChild(title);
panel.appendChild(item);
var latLng = new google.maps.LatLng(speedTest.pics[i].latitude,
speedTest.pics[i].longitude);
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=' +
'FFFFFF,008CFF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
var marker = new google.maps.Marker({
'position': latLng,
'icon': markerImage
});
var fn = speedTest.markerClickFunction(speedTest.pics[i], latLng);
google.maps.event.addListener(marker, 'click', fn);
google.maps.event.addDomListener(title, 'click', fn);
speedTest.markers.push(marker);
}
window.setTimeout(speedTest.time, 0);
};
speedTest.markerClickFunction = function(pic, latlng) {
return function(e) {
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
var title = pic.photo_title;
var url = pic.photo_url;
var fileurl = pic.photo_file_url;
var infoHtml = '<div class="info"><h3>' + title +
'</h3><div class="info-body">' +
'<a href="' + url + '" target="_blank"><img src="' +
fileurl + '" class="info-img"/></a></div>' +
'<a href="http://www.panoramio.com/" target="_blank">' +
'<img src="http://maps.google.com/intl/en_ALL/mapfiles/' +
'iw_panoramio.png"/></a><br/>' +
'<a href="' + pic.owner_url + '" target="_blank">' + pic.owner_name +
'</a></div></div>';
speedTest.infoWindow.setContent(infoHtml);
speedTest.infoWindow.setPosition(latlng);
speedTest.infoWindow.open(speedTest.map);
};
};
Here is the full code I m currently using:
speed_test_example.html
speed_test.js
When you create your marker, you can specify where the InfoWindow should be anchored, like:
var marker = new google.maps.Marker({
'position': latLng,
'icon': markerImage,
'anchorPoint': new google.maps.Point(x, y)
});
where x and y are the x and y offset from the marker's position.
Note: google.maps.MarkerImage is no longer used. Use Icon instead.
Related
So I've set up this simple map:
var map = L.mapbox.map('map', 'mapbox.streets')
.setView([52.15, 5.5], 8);
var myLayer = L.mapbox.featureLayer().addTo(map);
// Add custom popups to each using our custom feature properties
myLayer.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
// (stuff happens)
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 500
});
});
// the following is where it all goes wrong:
// Run easings when links are clicked
var side = document.getElementById('map-ui');
for (var i = 0; i < features.length; i++) { // for all the number of features we have
var a = side.appendChild(document.createElement('a')); // add a 'a' child to the side element
a.onclick = (function(feature, i) { // when you click on it
return function() {
map.setView( [ // centre the map to the appropriate coordinates
feature.geometry.coordinates[1],
feature.geometry.coordinates[0]+0.03 // +0.03 puts it a bit to the left, to make room for the tooltip
],12);
Here is where I want to open the popup but I'm not sure how to trigger the right marker to open up. For the real life example, visit www.boerenmetwater.nl. The following four examples don't work:
//marker()[1].openPopup();
//map.marker[i].openPopup();
//t.openPopup(this);
//marker.openPopup();
}
}
)
(features[i], i);
a.href = '#';
a.title = 'klik om naar ' + features[i].properties.plaats + ' te gaan';
a.innerHTML = '<div class = "menu_plaatsnaam">' + features[i].properties.plaats + '</div>';
a.innerHTML += '<div class = "menu_titel">' + features[i].properties.titel + '</div>';
}
Below is the code I am working with. I'm trying to fix an error with a map not displaying in all browsers.
In dev tools (chrome), I'm getting a Uncaught ReferenceError: google is not defined error.
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});
You need to wait until google has loaded before running your scripts. Put this somewhere in your document:
$(document).ready(function(){
//google map
function loadGoogleMap() {
var mapOptions = {
scrollwheel: false,
zoom: 14,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#map")[0], mapOptions);
var bounds = new google.maps.LatLngBounds();
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
var count = 0;
$.each(dealers, function(ind,dealer){
var point = new google.maps.LatLng(dealer.lat,dealer.lng)
var marker = new google.maps.Marker({
position: point,
map: map,
title: dealer.post_title,
icon: icons[count]
});
var infowindow = new google.maps.InfoWindow({
content:'<div class="infowindow">'+
'<strong>' + dealer.post_title + '</strong><br/>' +
'<address>' +
dealer.address1 + '<br/>' +
dealer.city + ', ' + dealer.state + '<br/>' +
'</address>' +
dealer.phone + '<br/>' +
(dealer.url != '' ? 'Dealer Website<br/>' : '') +
(dealer.email != '' ? 'Email Dealer<br/>' : '') +
'Get Directions'+
'</div>'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});
// add event listener to distributor list
$('#distributors-list li:eq(' + count + ')').click(function(){
infowindow.open(map,marker);
});
bounds.extend(point);
count++;
});
map.fitBounds(bounds);
}
loadGoogleMap();
// reuse fancybox loading icon script
var loadingTimer, loadingFrame = 1;
var locator_animate_loading = function() {
locatorLoading = $('#ajax-loading-overlay');
if (!locatorLoading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$(locatorLoading).css('background-position', '0 ' + (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$('form.distributor-search').submit(function(e){
locatorLoading = $('#ajax-loading-overlay');
locatorLoading.show();
loadingTimer = setInterval(locator_animate_loading, 66);
$('#locator-content').load(site_url + '/graceports/find-a-distributor?ajax=1&address=' + encodeURIComponent($('#address_search').val()) + ' #ajax-contents', function() {
// load updated list of dealers
$('#locator-content').append('<script src="' + site_url + '/js/dealers.php?address=' + encodeURIComponent($('#address_search').val()) + '"></script>');
loadGoogleMap();
locatorLoading.hide();
});
e.preventDefault();
});
navigator.geolocation.getCurrentPosition(function(position){
$.get(site_url + '/cms/wp-content/themes/grace/inc/latlng-to-zip.php?latlng=' + encodeURIComponent(position.coords.latitude + ' ' + position.coords.longitude), function(data){
$('#address_search').val(data);
$('form.distributor-search').trigger('submit');
});
});
});
I am using ajax and php and I grabbing all of the points out of my database and plotting them on the map. Which works fine. However I want to change the icon of the marker depending on if status in the database is 100 or 200 or 300 for each record. I can't seem to get anything to work. Here is my code:
if (localStorage.getItem('type2') !== null) {
$(function ()
{
var radius2 = localStorage.getItem("radius2");
var lat2 = localStorage.getItem("lat2");
var long2 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var city2 = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://example.com/Test/www/22233333.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
})
}
});
})
}
Looks like you are using jquery-ui-map?
I haven't used this abstraction
You can call the setIcon function - on a marker you can set it's icon this way for the main API
https://developers.google.com/maps/documentation/javascript/reference#Marker
So your addMarker method will return a marker instance by the look of it so once you have that run setIcon
Do something like this in your success function with in $.each.
Status is the database field
var size = val['size'];
var status = val['status'];
var icon = '';
if (status == 100){
icon = 'images/icon1.png'; //your icon1
}else if (status == 100){
icon = 'images/icon1.png'; //your icon2
}
...
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': icon //your dynamic icon
})
Hope this helps
I'm using a Google Maps plugin, and I want it to show up on the page load as well as all postbacks. It seems to only work on postbacks though. Any ideas? I have the body onload tag as "body background="#ccccff" onload="initialize()"", but the function is not defined the first time. Why? Here is the code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var mostRecentInfo;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
center: center,
zoom:1,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var posStr = <%=JSON%>;
if (posStr.toString() != "0") {
var test = posStr.toString().split(',');
var groundstation = <%=groundStation%>;
var dateTimeStr = <%=datetimesStr%>;
var AUStr = <%=auStr%>;
var spaceCraft = <%=spacecraft%>;
var dateTimes = dateTimeStr.toString().split(',');
var auIDs = AUStr.toString().split(',');
var latitude = new Array((test.length / 2));
var longitude = new Array(latitude.length);
var i = 0;
var markerArray = new Array();
for (var j = 0; j < (test.length - 1); j = j + 2) {
latitude[i] = eval(test[j+1]);
longitude[i] = eval(test[j]);
var position = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
map:map,
position:position
});
markerArray.push(marker);
i++;
}
var sumLat = 0;
var sumLong = 0;
for (i = 0; i < latitude.length; i++) {
sumLat += latitude[i];
sumLong += longitude[i];
}
var avgLat = sumLat / latitude.length;
var avgLong = sumLong / longitude.length;
center = new google.maps.LatLng(avgLat, avgLong);
map.panTo(center);
var circle;
var contentStr = new Array();
for (i = 0; i < markerArray.length; i++) {
position = markerArray[i].getPosition();
var circOptions = {
strokeColor:"#770000",
strokeOpacity:0.1,
fillColor:"#881111",
fillOpacity:0.4,
map:map,
center:position,
radius:2500000
};
circle = new google.maps.Circle(circOptions);
marker = markerArray[i];
contentStr[i] = '<div id="content">' +
'<b>Spacecraft: </b>' + spaceCraft.toString() + '<br />' +
'<b>Start Time (UTC): </b>' + dateTimes[i].toString() + '<br />' +
'<b>Position: </b>(' + latitude[i].toString() + ', ' + longitude[i].toString() + ')<br />' +
'<b>AU ID: </b>' + auIDs[i] + '<br />' +
'<b>Downlink Station: </b>' + groundstation.toString() + '<br />' +
'</div>';
addListener(map, marker, contentStr[i]);
}
}
}
function addListener(map, marker, content) {
var infowindow = new google.maps.InfoWindow({
content:content
});
google.maps.event.addListener(marker, 'mouseover', function() {
if (mostRecentInfo)
mostRecentInfo.close();
mostRecentInfo = infowindow;
infowindow.open(map, this);
});
}
etc.
It is likely a timing issue with the onload function being called before the initialize function is ready. This is the reason libraries like jQuery have a document.ready function. You can try removing the onload and place a call to initialize() at the bottom of your HTML, just prior to the closing body tag. This will probably work for you.
If you have the option, I'd use a library so you can assure that the function is there and your page is ready. If you haven't tried it, give jQuery a shot.
I'm not used to writing JS, honestly, and to make matters worse I'm working with the Google Maps API which, while well-documented, is a bear. So, I've written a function that allows a users to zoom onto the map from a link. But the interpreter insists my function isn't defined when I call it. The function is "zoomTo" and it appears in the following monster script.
function load() {
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var i = 0;
// Read the data
//++++++++++++++++
GDownloadUrl("/assets/data/nolag.xml", function(data) {
var xml = GXml.parse(data);
var markers =
xml.documentElement.getElementsByTagName("marker");
// Draw icons
for (var i = 0; i < markers.length; i++) {
var locoName = markers[i].getAttribute("locoName");
var speed = markers[i].getAttribute("speed");
var ip = markers[i].getAttribute("ip");
var date = markers[i].getAttribute("captureTime");
var lat = markers[i].getAttribute("lat");
var lng = markers[i].getAttribute("lng");
var location = markers[i].getAttribute("location");
var heading = markers[i].getAttribute("heading");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, locoName, speed, ip, date, lat, lng, location, heading, type);
map.addOverlay(marker);
}
});
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40.5500, -72.1700), 7);
map.enableScrollWheelZoom();
NEC = new GPolyline(NECRoute, "#0d004c", 3, 0.7);
map.addOverlay(NEC);
// A function to create the marker and set up the event window
//+++++++++++++++++
function createMarker(point, locoName, speed, ip, date, lat, lng, location, heading, type) {
var marker = new GMarker(point, customIcons[type]);
marker.tooltip = '<div class="tooltip"><h1>' + locoName + '</h1><h2>' + speed + '<br/>' + location + '</h2></div>';
marker.contextmenu = '<div class="contextmenu">Hello world</div>';
var satellite = "<img src=\"./images/icons/satellite.gif\">";
var gps = "<img src=\"./images/icons/gps.gif\">";
var cmu = "<img src=\"./images/icons/cmu.gif\">";
var ftp = "<img src=\"./images/icons/ftp.gif\">";
var me1k = "<img src=\"./images/icons/me1k.gif\">";
var html = "<div class=\"bubble\">";
html += "<h3>" + locoName + "<span class=\"small-data\"> Route 2150</span></h3>";;
html += "<div class=\"toolbar\">" + gps + satellite + cmu + ftp + me1k + "</div>";
html += "<h4>Heading " + heading + " # " + speed + " MPH</h4>"
html += "<h4>Lat: " + lat + "</h4><h4> Lng: " + lng + "</h4>";
html += "<h4>IP: " + ip + "</h4>";
html += "<h4><div class=\"sm-button\"><a style='color: #FFFFFF; decoration:none;' href='map_detail.php'>Details</a></div><div class=\"sm-button\">Zoom To</div></h4>";
html += "</div>";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
// ====== The new marker "mouseover" and "mouseout" listeners ======
GEvent.addListener(marker,"mouseover", function() {
showTooltip(marker);
});
GEvent.addListener(marker,"mouseout", function() {
tooltip.style.visibility="hidden"
});
return marker;
}
// ====== This function displays the tooltip ======
//+++++++++++++++++++++++++++++++++++++++++++++++++++
function showTooltip(marker) {
tooltip.innerHTML = marker.tooltip;
var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
var anchor=marker.getIcon().iconAnchor;
var width=marker.getIcon().iconSize.width;
var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
pos.apply(tooltip);
tooltip.style.visibility="visible";
}
// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
function mymouseover(i) {
showTooltip(gmarkers[i])
}
// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
function mymouseout() {
tooltip.style.visibility="hidden";
}
// This function picks up the side_bar click and opens the corresponding info window
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
// ====== set up marker mouseover tooltip div ======
var tooltip = document.createElement("div");
document.getElementById("map").appendChild(tooltip);
tooltip.style.visibility="hidden";
// === create the context menu div ===
var contextmenu = document.createElement("div");
contextmenu.style.visibility="hidden";
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
contextmenu.innerHTML = '<div class="context"><ul>'
+ '<li class="sectionheading">Zoom Out</li>'
+ '<li class="sectionheading">Boston Area</li>'
+ '<li>South Station, Boston</li>'
+ '<li>South Hampton</li>'
+ '<li>New Haven</li>'
+ '<li class="sectionheading">New York Area</li>'
+ '<li>Sunny Side</li>'
+ '<li>NY, Penn Station</li>'
+ '<li>30th Street, Philadelphia</li>'
+ '<li>Wilmington Shops</li>'
+ '<li>Baltimore, Penn Station</li>'
+ '<li class="sectionheading">DC Area</li>'
+ '<li>DC, Ivy City</li>'
+ '<li>DC, Union Station</li>'
+ '</ul</div>';
map.getContainer().appendChild(contextmenu);
// === listen for singlerightclick ===
GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
clickedPixel = pixel;
var x=pixel.x;
var y=pixel.y;
if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
pos.apply(contextmenu);
contextmenu.style.visibility = "visible";
});
// === If the user clicks on the map, close the context menu ===
GEvent.addListener(map, "click", function() {
contextmenu.style.visibility="hidden";
});
} else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
}
It appears that zoomTo is an annonymous function inside of the top-level function load() - therefore, it's not available to top-level calls.
Instead of
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
put the function in the top level, and pass in the map and contextmenu variables:
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
As it dont looks well in comment. posting the comment above here again
<html>
<head>
<script type="text/javascript">
function zoomTo(x,y,z) {
....
}
</script>
.....
</head>
......
</html>