Google Map API in WordPress without a plugin? - wordpress

I'm looking to simply add a google map using google maps api to one of my pages in WordPress. Is there a simple way of simply copy and pasting the "Hello, World" google maps code somewhere to have the map displayed on a page?
thanks

Yes, there's no need for a plugin for something like this. First of all you would include the Google maps script in header.php or you could enqueue it;
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
Then I normally add the following in header.php - this adds conditional code to the tag for the page containing the map only (in this case page 374);
<body <?php if (is_page(374)) { echo 'onload="initialize()" onunload="GUnload()"'; } ?>>
And then I would create a custom template for the contact page (as that's the page the map is normally on) and in the template for that page include something like the following. Yes, it's probably a bit long for a code sample but I'm just giving you a real example which contains an animated marker which can be clicked on to show your client's address. You could change the inline dimensions to suit your design, and you can also offset the map so the marker isn't right smack in the middle of it.
<div id="contact-content">
<script type="text/javascript">
function initialize() {
var leeds = new google.maps.LatLng(53.80583, -1.548903);
var firstLatlng = new google.maps.LatLng(53.80583, -1.548903);
var firstOptions = {
zoom: 16,
center: firstLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_leeds"), firstOptions);
firstmarker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.DROP,
title: 'Your Client',
position: leeds
});
var contentString1 = '<p>The Address<br />Of your client<br />in<br />here</p>';
var infowindow1 = new google.maps.InfoWindow({
content: contentString1
});
google.maps.event.addListener(firstmarker, 'click', function() {
infowindow1.open(map,firstmarker);
});
}
</script>
<div class="map">
<div id="map_leeds" style="width: 600px; height: 600px"></div>
</div>
</div>
If anyone else does it a different, better way then I'd be keen to see it, but I've used this on loads of sites and it works really well.

Related

Customize Google Places Map API "icon" InfoWindows

I am having trouble customizing the "clicked" infowindows in the google places API. I am able to use the places api to find locations and to customize the searched infoWindows (image 1) but I cannot seem to figure out how to customize the infoWindows launched by the places icons (image 2).
I apologize, part of my problem is I don't know what those specific infoWindows are called and if I did, I might be able to search for the solution. It seems most questions on this site are related to customizing the searched infoWindow content and I have had success doing that.
Searched Customized InfoWindow (image 1)
The InfoWindow that I want to customize and is launched by icons on the map (image 2)
Those are called clickableIcons. From the documentation
clickableIcons | Type: boolean
When false, map icons are not clickable. A map icon represents a point of interest, also known as a POI. By default map icons are clickable.
and:
getClickableIcons() | Return Value: boolean
Returns the clickability of the map icons. A map icon represents a point of interest, also known as a POI. If the returned value is true, then the icons are clickable on the map.
To control the InfoWindow, stop the default one from being opened, as described in the IconMouseEvent documentation:
google.maps.IconMouseEvent object specification
This object is sent in an event when a user clicks on an icon on the map. The place ID of this place is stored in the placeId member. To prevent the default info window from showing up, call the stop() method on this event to prevent it being propagated. Learn more about place IDs in the Places API developer guide.
proof of concept fiddle
code snippet:
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
});
var iw = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function(evt) {
evt.stop()
if (evt.placeId) {
console.log(evt.placeId);
iw.setContent(evt.placeId);
iw.setPosition(evt.latLng);
iw.open(map);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

How can I display Google Map field of Advanced Custom Fields plugin in front-end of my site?

I have used Google Map field of Advanced Custom Fields plugin to input map value from backend of my site. Can anyone suggest me best way to display it in frontend of my site?
I have tried the above accepted answer which didn't worked for me. The easy solution which I have found is to add the location using ACF plugin from the dashboard and display it using an iframe.
<iframe width="400" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.ca/maps?center=<?php the_field('maps'); ?>&q=<?php the_field('maps'); ?>&zoom=14&size=300x300&output=embed&iwloc=near"></iframe><br />
Here maps is the name of the custom google map field which I have created. Replace it with the your desired field name.
I found solution of using google map field of ACF. You can find documentation of ACF google map field here
If you don't want to use default script of ACF, you can consider following approach:
Add following div where you want to display the map:
<div id="map_canvas" style="height: 350px;width: 1200px; margin: 0.6em;"></div>
Add following codes in footer of your site above wp_footer
<?php $map = get_field('map', get_the_ID()); ?>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $map['lat']; ?>, <?php echo $map['lng']; ?>);
var myOptions = {
zoom: 11,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>

Google Maps - all buttons are disabled on load

I'm writing a Wordpress page for a client that displays some text and a Google Map based on data loaded from a database.
So far I've gotten most of it to work. The Google Maps however begins to load then mysteriously "blues" out displaying only what looks like ocean with all the other options (zoom in/out, street view, etc.) greyed out.
There are no JavaScript errors available from FireBug etc.
The divs containing the map (#container, and #map-canvas ) are set to real pixel values.
The solution given here yields no positive results.
This is what the end result looks like:
Any ideas would be extremely welcome.
Edit:
Code snip per request:
echo '<script>function initialize(e,t,n){e=parseFloat(e);t=parseFloat(t);var r=new google.maps.LatLng(e,t);var i;var s;var o={center:r,zoom:14,mapTypeId:google.maps.MapTypeId.ROADMAP};s=new google.maps.Map(document.getElementById("map-canvas"),o);i=new google.maps.Marker({map:s,draggable:false,animation:google.maps.Animation.DROP,position:r,title:n});google.maps.event.addDomListener(window,"load",initialize)}jQuery(function($){initialize("'.$detail['latitude'].'","'.$detail['longitude'].'","'.$detail['name'].'")})</script>';
echo '
<div id="container" style="height:500px;width:500px;">
<div id="information">
<h2>'.$detail['name'].'</h2>
<p>'.$detail['description'].'</p>
<p>'.$detail['address'].'</p>
</div>
<div id="map-canvas" style="width:300px;height:200px;">
</div>
</div>
';
Un-minified version of the JS:
function initialize(lat,lng,name) {
lat = parseFloat(lat);
lng = parseFloat(lng);
var ourLocation = new google.maps.LatLng(lat,lng);
var marker;
var map;
var mapOptions = {
center: ourLocation,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: ourLocation,
title:name
});
google.maps.event.addDomListener(window,"load",initialize);
};
jQuery(function($){
initialize(lat,lng,name);
// the variables lat, lng, and name are replaced with php variables in the code
});
I figured it out. Took a little while, but...
Wordpress hates the jQuery call for some reason or another.
I noticed that in the JS console, if I called the initialize function with the variables I'd rip from the generated source then the map would magically work.
Instead of using jQuery, I just used the windows onload event.
window.onload = function() { initialize('.$detail['latitude'].','.$detail['longitude'].',"'.$detail['name'].'"); }
Which magically works.
Lesson learned, jQuery and Wordpress are like Strawberry Chocolate Milk and India Pale Ales: they don't mix well.
Thank you everyone that contributed.

Pegman has disappeared from my map

For as long as I can remember, the street view pegman has appeared on my map. Today, I noticed that he doesn't appear (although if you know where to mouse over to grab him, you can still get a streetview happening). My zoom control has similarly disappeared (but is still there if you know where to mouse for it) but not on mobile devices where it seems to display just fine.
My first guess is that this is a bug in the Maps API that's been introduced recently. But specifying v=3.4 in the URL for the API doesn't correct the issue.
Am I doing something wrong? If not, is there a workaround?
Here's how I create the map:
<script type="text/javascript">
var lat=<?php echo $lat; ?>;
var lon=<?php echo $lon; ?>;
var initialZoom=<?php echo $initialZoom; ?>;
var mapTypeId = 'Custom Map';
var mapStyle = [{featureType:"administrative", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:22},{lightness:-5}]},
{featureType:"landscape", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:16},{lightness:-7}]},
{featureType:"road", elementType:"geometry", stylers:[{hue:"#ffffff"},{saturation:-100},{lightness:100}]}];
var styledMap = new google.maps.StyledMapType(mapStyle);
var mapType = new google.maps.ImageMapType({
tileSize: new google.maps.Size(256,256),
getTileUrl: function(coord,zoom) {
return "img/tiles/"+zoom+"/"+coord.x+"/"+coord.y+".png";
}
});
var map = new google.maps.Map(document.getElementById("map_canvas"),
{center:new google.maps.LatLng(lat,lon),
mapTypeId:google.maps.MapTypeId.ROADMAP,
zoom:initialZoom,
mapTypeControl:false});
map.overlayMapTypes.insertAt(0, mapType);
map.mapTypes.set(mapTypeId, styledMap);
map.setMapTypeId(mapTypeId);
</script>
I had recently added this CSS rule which was causing the problem:
img {
max-width: 100%;
}
Removing that rule fixed the problem.

How to use own map database to show a map on website?

How to use own map database to display map on a website and use that map to find route and do other stuff ?
You should try the Google Maps API. http://code.google.com/apis/maps/index.html
You can store locations or routes in your database and use the Maps API to display them. Not sure if this is what you're looking for, but I've found their API really easy to use.
That is an absolutely massive task, I'm not sure I understand your question correctly... You've tagged this with Javascript, Web-development and map - so presumably you want to know how to implement a front-end that renders a map to a web page, and then performs custom pathfinding and other logic. Surely I'm misunderstanding you! :D
The O'rielly RESTful Web Services book uses a map service as its operative example throughout the book, so you may find it useful, at least for the design of your service front end. It doesn't delve into the implementation very deeply, particularly the actual mechanics of map image generation, as it is primarily concerned with the design of the service interface from an HTTP perspective. It also doesn't treat very much with the client-side logic that would be involved in dragging, zooming and the like.
You have two options in order to calculate routes depending on your database.
If your database has clean and accurate address names then you can easily use the google maps API that can be found here: https://developers.google.com/maps/documentation/directions/.
Bare in mind that you can only execute 2500 requests per day with the free version.
On the other hand if you have a network defined on your db (have the roads in a nodes and arcs manner) then you can implement Dijsktra's algorithm.
Have a look here: http://www.vogella.com/articles/JavaAlgorithmsDijkstra/article.html
Because of the fact that the network should be loaded from the database in order to calculate the best route I suggest the singleton pattern.
An OpenSource way to do this, which I would recommend in most cases, is using GeoServer and OpenLayers.
GeoServer can read gegraphic data from all the major databases and be used as host for the widely used standard GeographicgWebServices WMS and WFS.
OpenLayers is a JavaScript API to show your map on the webpage.
I recently implemented something like this. I realize it is an old question but Google has the javascript api v3 out for Google Maps and it works great.
https://developers.google.com/maps/articles/phpsqlajax_v3
This page helped me implement the entire system. Works great. You can also use php to update and edit the entries on the map.
You need xml pages and others but here is the map html page just to give you an idea of the javascript it entails.
<!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>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

Resources