I cant seem to get it working. I used this on several other websites but with this new one it wont show my infowindow (infobox).
Markers are in position and when you are on a marker he is showing the title.
I can post the code but it comes with a lot of php and is a bit of a mess.
This is the url:
http://intertyre.server170.nognietactief.nl/montagepunten
I use the exact same sript on:
http://www.tyfoonbanden.nl/tyfoon-dealers
Working perfect.
Dont know why this is happening so if there is someone that knows what is causing the problem. Please share because I really dont know.
Thanks in advance.
The code (I know it is a mess, have to
<script type="text/javascript">
var geocoder;
var map;
var side_bar_html = "";
var gmarkers = [];
var infobox;
function initialize() {
// Create an array of styles.
var blueOceanStyles = [
{
featureType: "all",
elementType: "all",
stylers: [
{ saturation: -100 } // <-- THIS
]
}
];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: <?php
if(is_array($postcodevelden) && count($postcodevelden) > 0 && !empty($_POST['address']))
{
switch($radius)
{
case "5":
echo "12";
break;
case "10":
echo "11";
break;
case "15":
case "20":
echo "10";
break;
case "30":
case "40":
echo "9";
break;
}
}else{
echo "7";
}
?>,
center: new google.maps.LatLng(<?php if(is_array($postcodevelden) && count($postcodevelden) > 0) { echo $lat.", ".$lon; } else { echo "52.2008737173322, 5.25146484375"; } ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setOptions({styles: blueOceanStyles});
<?php
if(is_array($adressen) AND count($adressen) > 0)
{
foreach($adressen as $adres)
{
$afstand = round((6371 * acos(sin(deg2rad($lat)) * sin(deg2rad($adres->locatie_lat)) + cos(deg2rad($lat)) * cos(deg2rad($adres->locatie_lat)) * cos(deg2rad($adres->locatie_lon) - (deg2rad($lon))))), 2);
?>
addMarker(<?php echo $adres->locatie_lat.", ".$adres->locatie_lon.", '".$adres->locatie_naam."', '".$adres->locatie_straat."', '".$adres->locatie_postcode."', '".$adres->locatie_plaats."', '".$adres->locatie_telefoon."', '".$adres->locatie_website."', '".$afstand."'"; ?>);
<?php
}
}
?>
document.getElementById("table_markers").innerHTML = side_bar_html;
}
function myclick(i) {
map.setCenter(gmarkers[i].getPosition());
google.maps.event.trigger(gmarkers[i], "click");
}
var infowindow = new google.maps.InfoWindow({
content: document.getElementById("infobox"),
disableAutoPan: false,
maxWidth: 250,
pixelOffset: new google.maps.Size(0, 0),
zIndex: null,
boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
opacity: 0.95,
width: "280px"
},
closeBoxMargin: "12px 4px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1)
});
function addMarker(lat, lon, naam, straat, postcode, plaats, telefoon, website, afstand)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
icon: "/wp-content/uploads/wheel-icon.png",
title: naam
});
google.maps.event.addListener(marker, 'click', function() {
var contentString = '<div id="infobox">'+
'<b style="border-bottom: 1px solid #000000; color:#00377b;">' + naam + '</b><br/>'+
straat + '<br/>' +
postcode + ' ' + plaats + '<br/>';
if(telefoon != "")
{
contentString = contentString + telefoon + '<br/>';
}
if(website != "")
{
contentString = contentString + 'Website: <u><a target="_blank" rel="nofollow" href="http://' + website + '">' + website + '</a></u>';
}
contentString = contentString + '</div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
gmarkers.push(marker);
side_bar_html += '<table id="marker_list"><tr>'+ '<td onclick="javascript:myclick(' + (gmarkers.length-1) + ')"><a><h3>' + naam + '</h3>' + straat + '<br/>' + postcode + ' ' + plaats + '<br/>' + telefoon + '<br/>' + website + '<br/>' + '<u>Afstand ' + afstand + ' km</u>' +'</td>' +'<\/a></tr></table><br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<form action="/montagepunten" method="POST">
<input id="address" name="address" type="textbox"<?php if(isset($_POST['zoekpost']) && $_POST['zoekpost'] == 'zoek') { echo " value=\"".$_POST['address']."\""; } ?> style="float:left; height:30px; margin-right:10px; width:100px;"><select name="afstand" style="display:none;">
<option selected="selected" value="10">10 km</option>
</select>
<input type="submit" name="zoekpost" id="zoekpost" value="zoek">
</form>
<br/>
<br/>
<div class="mapborder">
<div class="map-width">
<div id="map_canvas"></div>
</div>
<div class="one_third-last" style="overflow-y:auto; overflow-x:hidden; height:579px; width:100%; clear:left; padding-top:0px; padding-bottom:0px; margin-top:20px;"><div id="table_markers"></div></div>
</div>
Problem solved...
Nothing wrong with the code but there was a conflict with loading google maps api multiple times.
Using Avada as Theme for website. For other users that run into this:
WP Dashboard > Appearance > Theme Options > Extra options page.
There you can disable the Google Maps Api for Avada and error is gone.
Related
I am using Google Maps to plot a number of pins and am having problems hiding empty strings within the info window.
All locations have a name and address but then there are 3 fields which will not necessarily all have a value.
These are:
telephone number
email address
website
var markersOnMap = [{
title: "Location One",
placeName: "Location One",
address: "Address",
telephone: "01234567890",
website: "http://somewebaddress.com",
emailaddress: "",
LatLng: [{
lat: 40.4319077,
lng: 116.5703749
}]
}];
I then put the information into a variable to output it.
var contentString = '<div id="content"><p>' + markersOnMap[i].placeName + '</p><p>' + markersOnMap[i].address + '</p><p>T: ' + markersOnMap[i].telephone + '</p><p>' + markersOnMap[i].website + '</p><p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p></div>';
In the example above, Location One, I would like to hide the email address as it does not have a value.
How do I check if the value of those strings are empty and then not output them on a per location basis.
If anyone can provide any assistance, that would be great.
You could use proper var and ternary operator (or if ) for check each content and set the proper html dinamic string code
aPlaceName = (markersOnMap[i].placeName !='' ? '<p>' + markersOnMap[i].placeName + '</p>' :'');
aAddress = (markersOnMap[i].address !='' ? '<p>' + markersOnMap[i].placeName + '</p>' :'');7
...
and build the contentString using the var
var contentString = '<div id="content">' + aPlaceName + aAddress..... +'</div>';
One option would be to build the contentString incrementally if the pieces exist:
var contentString = '<div id="content">'
if (!!markersOnMap[i].placeName)
contentString += '<p>' + markersOnMap[i].placeName + '</p>';
if (!!markersOnMap[i].address)
contentString += '<p>' + markersOnMap[i].address + '</p>';
if (!!markersOnMap[i].telephone)
contentString += '<p>T: ' + markersOnMap[i].telephone + '</p>';
if (!!markersOnMap[i].website)
contentString += '<p>' + markersOnMap[i].website + '</p>';
if (!!markersOnMap[i].emailaddress)
contentString += '<p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p>';
contentString += '</div>';
proof of concept fiddle
code snippet:
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
var markersOnMap = [{
title: "Location One",
placeName: "Location One",
address: "Address",
telephone: "01234567890",
website: "http://somewebaddress.com",
emailaddress: "",
LatLng: [{
lat: 40.4319077,
lng: 116.5703749
}]
},
{
title: "Location Two",
placeName: "Location Two",
address: "Address2",
emailaddress: "",
LatLng: [{
lat: 40.432,
lng: 116.58
}]
}
];
function initMap() {
var uluru = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersOnMap.length; i++) {
var marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
bounds.extend(marker.getPosition());
marker.addListener('click', (function(i) {
return function(evt) {
var contentString = '<div id="content">'
if (!!markersOnMap[i].placeName)
contentString += '<p>' + markersOnMap[i].placeName + '</p>';
if (!!markersOnMap[i].address)
contentString += '<p>' + markersOnMap[i].address + '</p>';
if (!!markersOnMap[i].telephone)
contentString += '<p>T: ' + markersOnMap[i].telephone + '</p>';
if (!!markersOnMap[i].website)
contentString += '<p>' + markersOnMap[i].website + '</p>';
if (!!markersOnMap[i].emailaddress)
contentString += '<p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p>';
contentString += '</div>';
infoWindow.setContent(contentString);
infoWindow.open(map, this);
}
})(i))
}
map.fitBounds(bounds);
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>' +
'<div id="bodyContent">' +
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
'sandstone rock formation in the southern part of the ' +
'Northern Territory, central Australia. It lies 335 km (208 mi) ' +
'south west of the nearest large town, Alice Springs; 450 km ' +
'(280 mi) by road. Kata Tjuta and Uluru are the two major ' +
'features of the Uluru - Kata Tjuta National Park. Uluru is ' +
'sacred to the Pitjantjatjara and Yankunytjatjara, the ' +
'Aboriginal people of the area. It has many springs, waterholes, ' +
'rock caves and ancient paintings. Uluru is listed as a World ' +
'Heritage Site.</p>' +
'<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">' +
'https://en.wikipedia.org/w/index.php?title=Uluru</a> ' +
'(last visited June 22, 2009).</p>' +
'</div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Ayers Rock)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
I am using JavaScript in HTML page to display GPS locations with markers and all these GPS locations are connected
I am trying to implement a map/direction based application using Google maps V3 API. So far I have been able to display the map and show directions for two locations selected. the first one is my current location , the second one is the location of costumer (his/her information exist in my database). All the markers are being displayed in the output properly.
To get directions to a location specified by coordinates, make it a google.maps.LatLng object. To get that from your data in the select, save the coordinates as a string in the value, then parse out the latitude and longitude to create the LatLng object.
save the coordinates in the option value:
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
parse those coordinates and create a google.maps.LatLng object in the directions request:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="afficher la direction" onclick="calculateRoute();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
Is it possible to zoom to a marker if it's inside a marker cluster? I am changing the color of the markers if a user hovers over a html div. But if the marker is inside a cluster, the color won't change since the marker itself is not shown. Could anyone provide me with possible ways of solving this issue?
var allMarkers = [];
(function($) {
"use strict";
// Custom options for map
var options = {
zoom: 12,
mapTypeId: 'Styled',
disableDefaultUI: true,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeControlOptions: {
mapTypeIds: ['Styled']
}
};
var styles = [{
stylers: [{
hue: "#cccccc"
}, {
saturation: -100
}]
}, {
featureType: "road",
elementType: "geometry",
stylers: [{
lightness: 100
}, {
visibility: "simplified"
}]
}, {
featureType: "road",
elementType: "labels",
stylers: [{
visibility: "on"
}]
}, {
featureType: "poi",
stylers: [{
visibility: "off"
}]
}];
var newMarker = null;
var markers = [];
// json for properties markers on map
var props = < ? php echo json_encode($map_flats); ? > ;
// custom infowindow object
var infobox = new InfoBox({
disableAutoPan: false,
maxWidth: 202,
pixelOffset: new google.maps.Size(-101, -285),
zIndex: null,
boxStyle: {
background: "url('images/infobox-bg.png') no-repeat",
opacity: 1,
width: "202px",
height: "245px"
},
closeBoxMargin: "28px 26px 0px 0px",
closeBoxURL: "",
infoBoxClearance: new google.maps.Size(1, 1),
pane: "floatPane",
enableEventPropagation: false
});
// function that adds the markers on ma
var addMarkers = function(props, map) {
$.each(props, function(i, prop) {
var latlng = new google.maps.LatLng(prop.position.lat, prop.position.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
id: +prop.id,
icon: new google.maps.MarkerImage(
'images/' + prop.markerIcon,
null,
null,
null
),
draggable: false,
animation: google.maps.Animation.DROP,
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
allMarkers.push(marker); //Add it to allMarkers
var infoboxContent = '<div class="infoW">' +
'<div class="propImg">' +
'<img src="uploads/' + prop.image + '">' +
'<div class="propBg">' +
'</div>' +
'</div>' +
'<div class="paWrapper">' +
'<div class="propTitle">€' + prop.title + '</div>' +
'<div class="propAddress">' + prop.address + '</div>' +
'</div><br>' +
'<ul class="propFeat">' +
'<li><span class="fa fa-moon-o"></span> ' + prop.bedrooms + ' room(s)</li>' +
'<li><span class="icon-frame"></span> ' + prop.area + ' m<sup>2</sup></li>' +
'</ul>' +
'<div class="clearfix"></div>' +
'<div class="infoButtons">' +
'<a class="btn btn-sm btn-round btn-gray btn-o closeInfo">Close</a>' +
'<a target="_blank" href="single.php?id=' + prop.id + '" class="btn btn-sm btn-round btn-green viewInfo">View</a>' +
'</div>' +
'</div>';
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infobox.setContent(infoboxContent);
infobox.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, "click", function(event) {
infobox.close();
});
$(document).on('click', '.closeInfo', function() {
infobox.open(null, null);
});
markers.push(marker);
});
//set style options for marker clusters (these are the default styles)
var mcOptions = {
styles: [{
height: 53,
url: "images/m1.png",
width: 53
}, {
height: 54,
url: "images/m1.png",
width: 54
}, {
height: 66,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
width: 66
}, {
height: 78,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png",
width: 78
}, {
height: 90,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png",
width: 90
}],
gridSize: 50,
maxZoom: 14
}
//init clusterer with your options
var mc = new MarkerClusterer(map, markers, mcOptions);
The Cluster doesn't change color (yet ?). But I do have code that detects if the client hovers over his marker inside the cluster. So, now it logs a message onyour screen.
Look at the scripts I load. Google Maps, MarkerClustererPlus and a script containing data. Many locations (of photographs).
So, the marker of the client, is the marker in Central Park, New York, USA.
Try it out.
Any other idea how to visualize the detection? Like add a circle around the cluster, ... ?
<script src="http://maps.google.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/examples/data.json"></script>
<script>
var client_index = 821; // Central Park, New York. Item 821 ( "photo_id": 586159 )
// We run through all the marker-objects inside the cluster; and we see if the marker object of our client marker is inside that array
function clientMarkerInCluster(allMarkers, markersInCluster) {
if(markersInCluster.indexOf( allMarkers[client_index] ) > 0) {
return true;
}
return false;
}
function initialize() {
var center = new google.maps.LatLng(40.480467417349345,-98.80444335937501);
var options = {
'zoom': 4,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for(var key in data.photos) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(data.photos[key].latitude, data.photos[key].longitude),
map: map,
title: key +' '+ data.photos[key].photo_title
})
);
}
var mcOptions = {gridSize: 50, maxZoom: 15};
var mc = new MarkerClusterer(map, markers, mcOptions);
google.maps.event.addListener(mc, "mouseover", function (c) {
if(clientMarkerInCluster(markers, c.markers_)) {
log('Client marker is inside the cluster');
}
});
// google.maps.event.addListener(mc, "mouseout", function (c) {});
}
google.maps.event.addDomListener(window, 'load', initialize);
// just a function to show a log on screen
function log(h) {
document.getElementById("log").innerHTML += h + "<br>";
}
</script>
<style>
#map {
height: 400px;
}
</style>
<div id="map"></div>
<div id="log"></div>
I have been developing the practice of URL: https://developers.google.com/maps/articles/phpsqlinfo_v3 and it works, but in another example I need that the same window HTML form appears when i click the marker that shows on the map when i use the code to geolocate my position and to save that information into a MySQL database. I'm using the code below but the HTML form window does´nt appear to save the geolocation data.
This is the code used in the webpage: phpsqlinfo_add.html (similar name of the URL Sample: https://developers.google.com/maps/articles/phpsqlinfo_v3) The other complementary webpages: phpsqlinfo_addrow.php and phpsqlinfo_dbinfo.php are similar to the example.
CODE OF: phpsqlinfo_add.html
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>:: DEMO ::</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}
function init() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var marcador = new google.maps.Marker();
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marcador.setPosition(pos);
marcador.setMap(map)
}, function() {
alert("Su navegador debe soportar geolocalizacion");
});
}
}
google.maps.event.addDomListener(window, 'load', init);
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var html = "<table>" +
"<tr><td>Nombre:</td> <td><input type='text' id='name' value='Juan Gomez' readonly='readonly' /> </td> </tr>" +
"<tr><td>Direccion:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Tipo:</td> <td><select id='type'>" +
"<option value='Opcion 1' SELECTED>Opcion 1</option>" +
"<option value='Opcion 2'>Opcion 2</option>" +
"<option value='Opcion 3'>Opcion 3</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Registrar' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map_canvas
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
function saveData() {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Ubicacion Registrada.";
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<div id="message"></div>
</body>
</html>
The code adding the onclick event listeners & creating the infowindow was never being activated, plus you are referencing the map_canvas div instead of your map. Try this (see // * my comments * for changes):
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}
function init() {
// * adjusted geolocation code for testing *
var pos = new google.maps.LatLng(51.511,0.275);
var marcador = new google.maps.Marker();
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marcador.setPosition(pos);
marcador.setMap(map)
// * infowindow code wasn't being activated, moved inside init() function *
var html = "<table>" +
"<tr><td>Nombre:</td> <td><input type='text' id='name' value='Juan Gomez' readonly='readonly' /> </td> </tr>" +
"<tr><td>Direccion:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Tipo:</td> <td><select id='type'>" +
"<option value='Opcion 1' SELECTED>Opcion 1</option>" +
"<option value='Opcion 2'>Opcion 2</option>" +
"<option value='Opcion 3'>Opcion 3</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Registrar' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
// * changed map: map_canvas to map: map *
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', init);
// * don't need to create map again *
// var map = new google.maps.Map(document.getElementById("map_canvas"), options);
// * rest of code should be fine... *
Also be careful with the <body onLoad="initialize()"> and google.maps.event.addDomListener(window, 'load', init); If this is not a mistake and initialize() does something different then it would be better to combine init() and initialize().
I'm having an issue where the content in my popup (when marker clicked) is showing the content of my last record.
I found a bit of help here, but I'm still having issues.
here's my code
collection.js
[
{
"lat": "-25.363882",
"lng": "131.044922",
"category": "cat1",
"title": "Heading #1",
"description": "desc1",
"imageurl": "http://ursispaltenstein.ch/blog/images/uploads_img/national_geographic_wallpaper_1.jpg",
"pageLink": "http://www.google.com"
},
{
"lat": "-26.363882",
"lng": "200.044922",
"category": "cat2",
"title": "Heading #2",
"description": "desc2",
"imageurl": "http://www.creativepics.org/wp-content/uploads/2009/10/National-Geographic-Wallpapers-002.jpg",
"pageLink": "http://www.google.com"
}
,
{
"lat": "-28.363882",
"lng": "81.044922",
"category": "cat3",
"title": "Heading #3",
"description": "desc3",
"imageurl": "http://blog.rapidsea.com/wp-content/uploads/2008/03/20080316-bora-bora-national-geographic.jpg",
"pageLink": "http://www.google.com"
}
]
page javascript
var pointMap = { map: null }
$(function () {
pointMap.init('#map_canvas', new google.maps.LatLng(0, 0), 2);
pointMap.placeMarkers('collection.js');
});
pointMap.init = function (selector, latLng, zoom) {
var myOptions = {
zoom: zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
this.map = new google.maps.Map($(selector)[0], myOptions);
}
pointMap.placeMarkers = function (filename) {
$.getJSON(filename, function (data) {
for (var x = 0; x < data.length; x++) {
var location = data[x];
var point = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
var marker = new google.maps.Marker({
position: point,
map: pointMap.map,
title: location.title
});
var popupContent = '<div id="locationContent">' +
'<div>' + location.category + '</div>' +
'<div>' + location.title + '</div>' +
'<div>' + location.description + '</div>' +
'<div>See This Story >></div>' +
'<div><img width="250" src="' + location.imageurl + '" /></div>' +
'</div>';
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(popupContent);
infoWindow.open(pointMap.map, this);
});
}
});
}
html
<!DOCTYPE html>
<html>
<head>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// javascript from above
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
The markers all load in the correct places and windows all open in the correct places, but the content loaded in the InfoWindow (popupContent) is of my last record for all the markers.
thanks for any help
So i've instead pushed the creation of the infoWIndow to a separate function instead of in the loop, and it seems to work.
updated code
pointMap.placeMarkers = function (filename) {
$.getJSON(filename, function (data) {
for (var x = 0; x < data.length; x++) {
var location = data[x];
var point = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
var marker = new google.maps.Marker({
position: point,
map: pointMap.map,
title: location.title
});
var popupContent = '<div id="locationContent">' +
'<div>' + location.category + '</div>' +
'<div>' + location.title + '</div>' +
'<div>' + location.description + '</div>' +
'<div>See This Story >></div>' +
'<div><img width="250" src="' + location.imageurl + '" /></div>' +
'</div>';
createInfoWindow(marker, popupContent);
}
});
}
var infoWindow = new google.maps.InfoWindow();
function createInfoWindow(marker, popupContent) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(popupContent);
infoWindow.open(pointMap.map, this);
});
}