Integrating Google Maps w/ WordPress - Infowindow not opening - javascript

I am currently trying to incorporate a map on the homepage of my wordpress blog which will display a custom icon on a map based on a post content and customfield location. I am very close and got everything working except the infowindow. I get no errors and no window. Your help is much appreciated.
I looked at similar questions and tried a few things but nothing worked.
Here is my code:
<script type="text/javascript">
function initialize() {
// setup map
var latlng = new google.maps.LatLng(34.109739, -118.351936);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var infowindow = new google.maps.InfoWindow();
// icons
var bootIcon = '/images/icons/bootIcon.png';
var hikingIcon = '/images/icons/hikingIconSm.png';
// Init post Data
var i = 0;
var hikingPositions = new Array();
var hikingMarkers = new Array();
var hikingBlurbs = new Array();
<?php $hiking_query = new WP_Query('category_name=hiking_ctg&posts_per_page=4');
while ($hiking_query->have_posts()) : $hiking_query->the_post();?>
<?php $geoLoc = get_post_meta($post->ID, 'longlat', true); ?>
// Set Post data
hikingPositions[i] = new google.maps.LatLng(<?php echo $geoLoc; ?>);
hikingMarkers[i] = new google.maps.Marker({
position: hikingPositions[i],
map: map,
icon: hikingIcon,
title:"<?php the_title(); ?>"
});
hikingBlurbs[i] = '<div id="content"><h1 id="firstHeading" class="firstHeading"><?php the_title(); ?></h1><div id="bodyContent"><p>.</p></div></div>';
i++;
<?php endwhile; ?>
// Assign data to map
for(var j=0, marker; j < hikingMarkers.length; j++)
{
// To add the marker to the map, call setMap();
hikingMarkers[j].setMap(map);
marker = hikingMarkers[j];
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(hikingBlurbs[j]);
infowindow.open(map,this);
});
}
}
$(document).ready(function() {
initialize();
});
</script>
I still have a long way to finish all the functionality I am looking for, but for this build, this is the only thing not working.
Thanks in advance.
Regards,
GeneralChaos

I am sure there are more elegant solutions to this, but this worked.
I noticed that the event handler I was using was receiving the index only when the loop was over so I changed the marker to 'this' and added an 'content' value to the marker object.
Define the content array before the marker:
hikingBlurbs[i] = '<div id="infowindowContent"><h1><?php the_title(); ?></h1><div id="bodyContent"><p>.</p></div></div>';
Define your marker with the new content variable:
// Set Post data
hikingPositions[i] = new google.maps.LatLng(<?php echo $geoLoc; ?>);
hikingMarkers[i] = new google.maps.Marker({
position: hikingPositions[i],
map: map,
icon: hikingIcon,
title:"<?php the_title(); ?>",
content: hikingBlurbs[i]
});
Now add the event listener with some simple changes:
// Assign data to map
for(marker in hikingMarkers)
{
google.maps.event.addListener(hikingMarkers[marker], 'mouseover', function() {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
}
Let me know if you see a better way of doing this or you have any questions.
Best Regards,
GeneralChaos

Related

How to display multiple colour pins on Google Maps

I am currently displaying markers on a Google Map successfully, but want to overlay a different set of markers in a different colour for something else but I'm a bit stuck on how to do it.
I am getting the data into the $markers array from a database as follows:
while($row = $result->fetch_row())
{
$rows[]=$row;
$markers[$key] = trim($row[12]).','.trim($row[13]).','.trim($row[10]).','.trim($row[9]).','.trim($row[8]).','.trim($row[4]).','.trim($row[6]).','.trim($row[3]);
$key = $key +1;
}
Where the $row[""] is the data from the database including lat and lon for the marker locations.
The magic then happens in here:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<?=$api_key?>">
</script>
<script type="text/javascript">
var map;
var marker = {};
function initialize() {
var mapOptions = {
center: { lat: 20.1788823, lng: 13.8262155},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var markers = [];
<?php
$counter = 0;
foreach ($markers as $index => $list){
$marker_details = explode(',',$list);
echo 'markers["m'.($index-1).'"] = {};'."\n";
echo "markers['m".($index-1)."'].lat = '".$marker_details[0]."';\n";
echo "markers['m".($index-1)."'].lon = '".$marker_details[1]."';\n";
$counter++;
}
?>
var totalMarkers = <?=$counter?>;
var i = 0;
var infowindow;
var contentString;
for (var i = 0; i<totalMarkers; i++){
contentString = '<div class="content">'+
'<h2 class="firstHeading">'+markers['m'+i].name+'</h2>'+
'<div class="bodyContent">'+
'<p>'+markers['m'+i].content+'</p>'+
'</div>'+
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker['c'+i] = new google.maps.Marker({
position: new google.maps.LatLng(markers['m'+i].lat,markers['m'+i].lon),
icon: {
url: "https://maps.google.com/mapfiles/ms/icons/red.png"
},
map: map,
title: markers['m'+i].name,
infowindow: infowindow
});
//console.log(markers['m'+i].lat+','+markers['m'+i].lon);
google.maps.event.addListener(marker['c'+i], 'click', function() {
for (var key in marker){
marker[key].infowindow.close();
}
this.infowindow.open(map, this);
});
}
}
function panMap(la,lo){
map.panTo(new google.maps.LatLng(la,lo));
}
function openMarker(mName){
//console.log(marker);
for (var key in marker){
marker[key].infowindow.close();
}
for (var key in marker){
if (marker[key].title.search(mName) != -1){
marker[key].infowindow.open(map,marker[key]);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And finally it is rendered with this:
<div id="map-canvas"></div>
I have tried reading the second set of data from another data into $markers2[$key] but I'm then stuck at what to do next, I've tried quite a few different things (too many to list here!) but it either fails to render the new markers of fails to render anything at all on the map.
Any pointers in the right direction would be helpful. I'm not too familiar with javascript unfortunately.
Ok, I found the problem, the issue was that I was creating another "new" map each time and needed to remove the additional instances of :
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
Now the additional markers with the new data display correctly.
Thanks for all the downvotes, it really does concentrate the mind on finding the solution yourself!

Creating an interactive InfoWindow Google Maps API

I'm trying to essentially allow the user to click options in the Google Map infowindow which would alter the content of that infowindow, i.e a page a,b,c inside the infowindow which when initially opened starts on a.
I've tried using jQuery at the top of the page (outside of the infowindow)
of the form
$(document).ready(function(){
$("#other1").click(function(){
$("#thingy").slideToggle("slow");
$("#squirry").slideToggle("slow");
});
});
and giving them id="something" inside the contentvar but to no avail
I've also tried having javascript of the form
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
inside the infowindow but I just get a whitescreen of death. Is there anyway you can put javascript within the html within the javascript? or anyway to allow the content of an infowindow to be changed from within the window once its already loaded.
Here is the code i'm looking at
its javascript/html nested inside some php
echo "
var myLatLng$i = {lat: $lat[$i], lng: $lng[$i]};
var image = 'nuticon.png';
var address$i = new google.maps.Marker({
position: myLatLng$i,
icon: image,
map: map});
address$i.addListener('click', function() {
document.getElementById('right-panel').innerHTML = '';
var contentString$i =
'<div id=\"content\">'+
'<div id=\"siteNotice\">'+
'</div>'+
'<h1 id=\"firstHeading\" align=\"center\" class=\"h3\">$titles[$i] </h1>'+
'<table border=\"1\" align=\"center\"><tr><p><td><b>Info</b></td><td> <b>Menu </b></td><td><b>Pictures</b></td></p></tr></table>'+
'<div id=\"bodyContent\" align=\"center\">'+
'<p></p>'+
'<iframe id=\"iframe\" src=\"http://voting.first-jump.com/init.php?a=g&g=1000000000004$i&m=0&n=5&s=25&nosound=1&f=3.png&f_a=&f_b=&f_c=\" allowtransparency=\"true\" hspace=\"0\" vspace=\"0\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" height=\"38\" scrolling=\"no\" width=\"128\"></iframe>'+
'</div>'+
'<p align=\"center\" id=\"logo\" ><img src=\"$i.png\" width=\"120\" onclick=\"window()\"></p>'+
'<p align=\"center\" id=\"weblink\">Website Link: <a href=\"$websites[$i]\">'+
'$titles[$i]</a> '
'</div>';
var infoWindow$i = new google.maps.InfoWindow({
map: map,
content: contentString$i,
maxWidth: 200
});
infoWindow$i.open(map, address$i);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.setOptions( { suppressMarkers: true } );
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute(pos, '$lat[$i],$lng[$i]', directionsService,
directionsDisplay);
});
";
}}}
?>
for those people trying to add tabs to your infowindow, try the infobubble library provided by Google
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/examples/example.html/
provides as good a working example as I myself would post.

Markers not appearing on Google Map using wp_query to find points

I am using the WP Favorite Posts plugin to allow users to select their favourite tours on the site. The posts are saved using to cookies to a saved template provided by the plugin. I have edited this template to include a map and to pull the coordinates from a Custom Meta Field.
The full template can be found at http://pastebin.com/zDrr5fPn.
The code I have included to display the map is:
<div id="map" style="width: 100%; height: 250px; position: relative; overflow: hidden; -webkit-transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
and the code I am using for the loop is:
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_meta($post->ID, 'custom_latlng', true) !== '' ) : ?>
<div style="display:block;">
<script type="text/javascript">
function initialize() {
//load map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(53.3498, -6.2603),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
var savedMarkers = new Array();
<?php $saved_pos = get_post_meta($post->ID, 'custom_latlng', true);?>
function addMarker() {
var savedMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(<?php echo $saved_pos ?>),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
});
savedMarkers.push(savedMarker);
}
}
</script>
</div>
At the moment, when I view the source, I can see the points being selected, the coordinates do appear. However they do not appear on the map itself. It is as if the points are appearing in the list of saved posts but not on the map at all.
I hope this makes sense.
Cheers
Inside the loop only populate an array with the latitudes/longitudes, create initialize outside of the loop:
<div id="map" style="width: 100%; height: 250px;"></div>
<script type="text/javascript">
function initialize() {
//load map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(53.3498, -6.2603),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
});
}
}
<?php
//create a php-array to store the latitudes and longitudes
$savedMarkers=array();
//use the loop to populate the array
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_meta($post->ID, 'custom_latlng', true) !== '' ) :
$savedMarkers[]=explode(',',get_post_meta($post->ID, 'custom_latlng', true));
endif;
endwhile;
?>
//print the array as js-variable
savedMarkers= <?php echo json_encode($savedMarkers);?>;
</script>
It's not tested, there may be some errors, but it should be sufficient to demonstrate the workflow.
Related to the comments:
To apply the post-title as infowindow-content also store the title in the savedMarkers-items:
$savedMarkers[]=array_merge(explode(',',get_post_meta($post->ID, 'custom_latlng', true)),
array(get_the_title()));
when you create the marker create a custom property for the marker where you store the infowindow-content(let's call the property content):
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
//the content(post-title)
content: savedMarkers[i][2]
});
}
Now use this content as infowindow-content:
google.maps.event.addListener(savedMarkers[i], 'click', function() {
infowindow.setContent(this.get('content'));
infowindow.open(this.getMap(), this);
}
);
You may also create a link to the posts inside the infowindows:
$savedMarkers[]=array_merge(explode(',',get_post_meta($post->ID, 'custom_latlng', true)),
array(get_the_title(),get_permalink()));
......
//create the markers
for(var i=0;i<savedMarkers.length;++i){
savedMarkers[i] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(savedMarkers[i][0],
savedMarkers[i][1]),
icon: '/wp-content/themes/dublin-visitors-centre/images/saved_icon.png',
//the content(post-title)
title: '' + savedMarkers[i][2],
//post-URL
href: savedMarkers[i][3]
});
}
..........
google.maps.event.addListener(savedMarkers[i], 'click', function() {
var link=document.createElement('a');
link.appendChild(document.createTextNode(this.get('title')));
link.setAttribute('href',this.get('href'));
infowindow.setContent(link);
infowindow.open(this.getMap(), this);
}
);

Replace Google Map marker with Instagram image

I'm working with the Instagram and google API. I'm trying to create thumbnail images from instagram to replace the markers on a Google Map by storing the longitude and latitude from the Instagram images. I am able to make the markers clickable to show the images but I would like to replace the markers to show small thumbnails instead (similar to the instagram map function http://www.topnews.in/files/instagram-photo-map.jpg)
Here is my code;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<?php
$lat = "";
$long = "";
function getMarkers(){
global $lat ;
global $long ;
$request ="https://api.instagram.com/v1/media/search? lat=".$lat."&lng=".$long."&access_token=__";
$crl = curl_init(); //creating a curl object
$timeout = 10; //so it stops getting info after failing for more than number
curl_setopt ($crl, CURLOPT_URL, $request);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$json = curl_exec($crl); //perhaps should be called $xml_to_parse!
curl_close($crl); //closing the curl object
$json1 = json_decode($json, true);
$json2 = json_decode($json);
//$decodeSearch = json_decode($searchlocation, true);
//$searchlocation = $instagram- >mediaSearch("","","","",20);
$dataCount = count($json2->data);
$dataObjects = $json2->data;
foreach($dataObjects as $currentObject) {
echo "[".$currentObject->location->latitude.",".$currentObject- >location->longitude.",'".$currentObject->images->low_resolution->url."'],";
}
}// close function
?>
<!-- this key belongs to Tamsin! -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js? key=__&sensor=false">
</script>
<script type="text/javascript">
var map;
var marker;
var markersArray = [<?php getMarkers(); ?>];
function initialize() {
var infoWindow = new google.maps.InfoWindow;
var myLatLong = new google.maps.LatLng(<?php echo "".$lat.",".$long.""; ?>);
var mapOptions = {
center: myLatLong,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// loop around markersArray
for(var i = 0; i < markersArray.length; i++){
var html = "<img src='"+markersArray[i][2]+"' />";//url
myLatLong = new google.maps.LatLng(markersArray[i][0],markersArray[i][1]);
marker = new google.maps.Marker({
position: myLatLong,
map: map,
});
bindInfoWindow(marker, map, infoWindow, html);
}
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, this);
});
}
</script>
</head>
You can use Custom Markers on Google Maps.
You can either select an icon from the available library, or use an image URL of your own as a marker, for instance an Instagram picture URL as described below:
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
animation: google.maps.Animation.DROP,
icon: {
url: 'http://distilleryimage10.s3.amazonaws.com/ee6a320caaa711e2b60722000a9f09f0_5.jpg',
size: new google.maps.Size(32, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(16, 16),
scaledSize: new google.maps.Size(32, 32)
}
});
Please take a look at the Complex Icons documentation to have more information about attributes about size and position of your markers like some I used above the resize the icon to 32x32 pixels.

Google map v2 to v3 code

I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {

Categories