I can't figure out how to add Marker Clusters to this map. It's used with Wordpress, so that the user can add locations to it from the Wordpress dashboard. I'm pretty new to Google API and I'm not having success with any examples that I find. Any help is appreciated!
<?php // Index template
get_header(); ?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div class="twelve column">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="intro">
<?php the_excerpt(); ?>
<hr>
</div>
<?php the_content(); ?>
<header class="clearfix"></header>
<div id="mapcanvas"></div>
<?php
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=locations'); // exclude category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
s <?php if(get_field('link')): ?>
<div>
<?php while(has_sub_field('link')): ?>
<div>
<p><?php the_sub_field('url'); ?></p>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<?php
function get_single_term($post_id, $taxonomy)
{
$terms = wp_get_object_terms($post_id, $taxonomy);
if(!is_wp_error($terms)) {
return ''.$terms[0]->name.'';
}
}
$i = 0;
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=location&posts_per_page=-1');
while($custom_query->have_posts()) : $custom_query->the_post();
$title = get_the_title(); // Location title
$map = get_field('location'); // ACF location contains address and coordinates
$terms = strip_tags( get_the_term_list( $post->ID, 'distributors', '', ' & ' )); // Get distributor terms and rm links
$info = '<strong>' . $title . '</strong><br>' . $map['address']; // Info window content
$link = get_field('link');
if($link){
$info .= '<br>'. $link .'';
}
$location[$i][0] = $title; // Store the post title
$location[$i][1] = $map['coordinates']; // Store the ACF coordinates
$location[$i][2] = json_encode($info); // Store info window content
$location[$i][3] = strip_tags( get_single_term( $post->ID, 'distributors' )); // Get first term for marker icon
$i ++;
endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<script>
var geocoder;
var map;
$(function initialize() {
geocoder = new google.maps.Geocoder();
// Center map on our main location
var myLatLng = new google.maps.LatLng(41.583013,-93.63701500000002);
var bounds = new google.maps.LatLngBounds();
// https://developers.google.com/maps/documentation/javascript/styling
// Create an array of styles.
var styles = [
{
stylers: [
{ saturation: -99.9 }
]
}
];
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles, {name: 'exile'});
// Create a map object, and include the MapTypeId to add
// to the map type control.
var mapOptions = {
mapTypeId: 'roadmap',
center: myLatLng,
zoom: 14,
disableDefaultUI: false,
scrollwheel: true,
draggable: true
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
map.setTilt(45);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('exile', styledMap);
map.setMapTypeId('exile');
// Marker icons
typeObject = {
"Others" : {
"icon" : new google.maps.MarkerImage('http://exilebrewing.com/site/img/beer-mug.png', new google.maps.Size(18,26), new google.maps.Point(0,0), new google.maps.Point(9,26)),
"shadow" : new google.maps.MarkerImage('http://maps.google.com/mapfiles/shadow50.png', new google.maps.Size(40,34))
}
}
// http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
// Multiple Markers
var markers = [
["Exile Brewing Co", 41.583013,-93.63701500000002,"Others"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)){
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"], ' . "\n";
} else {
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"]';
}
}
}
?>
];
// Info Window Content
var infoWindowContent = [
["<strong>Exile Brewing Co.</strong><br>1514 Walnut Street, Des Moines"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)) {
echo '[' . $location[$key][2] . '], ' . "\n";
} else {
echo '[' . $location[$key][2] . ']';
}
}
}
?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]); // ACF coordinates
var icon = typeObject[markers[i][3]]['icon'];
var shadow = typeObject[markers[i][3]]['shadow'];
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: icon,
shadow: shadow
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
//map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(15);
google.maps.event.removeListener(boundsListener);
});
});
</script>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
<footer class="clearfix"></footer>
<?php endwhile;?>
<?php endif; ?>
</div>
</div>
<?php get_footer(); ?>
Some
There can be three kind of clustering of markers as follows
Grid-Based Clustering
Grid-based clustering is probably the most common approach for clustering markers. It will divide the map into a grid and group all markers within each square into a cluster. Although an efficient technique, it has some obvious limitations since it can lead to unwanted results. Two markers that are really close together but in separate squares will, for example, not be grouped into the same cluster.
Distance-Based Clustering
This technique looks at each individual marker and checks whether it’s nearby other markers. If it’s close enough to another marker, the two of them will be grouped into a cluster.
Distance-based clustering also has its drawbacks. Since the clusters will appear at random
locations depending on where a cluster is formed they may not make sense for the user.
Regional Clustering
A third technique is regional clustering. What this means is that you define different geographical regions, such as counties or states. All markers in each region will be grouped into a cluster. You also define at which zoom level the cluster will break up into separate markers (or smaller clusters). The advantage of this technique is that you can create clusters that make more sense to the user. The drawback is that it requires more effort and can’t as easily be automated as the other clustering techniques.
Example
Shows the complete code. When you run this page, it will add 100 markers at random
locations at the visible part of the map. If you want to try adding a different number of markers, just change the number in the for loop.
(function() {
window.onload = function(){
// Creating a map
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
// Getting the boundaries of the map
var bounds = map.getBounds();
// Getting the corners of the map
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
// Calculating the distance from the top to the bottom of the map
var latSpan = northEast.lat() - southWest.lat();
// Calculating the distance from side to side
var lngSpan = northEast.lng() - southWest.lng();
// Creating a loop
for (var i = 0; i < 100; i++) {
// Creating a random position
var lat = southWest.lat() + latSpan * Math.random();
var lng = southWest.lng() + lngSpan * Math.random();
var latlng = new google.maps.LatLng(lat, lng);
// Adding a marker to the map
new google.maps.Marker({
position: latlng,
map: map
});
}
});
};
})();
Try this
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(13.696516,-89.208765);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var contentString = '<h1>Aditivos de El salvador</h1><p>33 Av. Sur #661, Colonia Flor Blanca, San Salvador El Salvador.</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var image = '<?php echo bloginfo('template_url'); ?>/images/iconmapa.png';
var beachMarker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image
});
google.maps.event.addListener(beachMarker, 'click', function() {
infowindow.open(map,beachMarker);
});
}
</script>
Related
Having trouble with this page loading my google map correctly. I am trying to help a friend with this but I am stumped. The script to call in the API key is in there once but I am getting the following errors:
You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
Invalid Map Key
Am I formatting this wrong?
<?php
$lat = 41.01413965527589;
$long = -102.53826150000003;
$pg_lat = get_field('pg_latitude');
$pg_long = get_field('pg_longitude');
if ( !is_null($pg_long) ) {
$long = $pg_long;
}
if ( !is_null($pg_lat) ) {
$lat = $pg_lat;
}
$map_theme = get_field('pg_map_styles');
$styles_file = get_template_directory() . '/assets/styles/map_styles.json';
$map_styles = file_get_contents($styles_file);
?>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AlzaSyBYE1TZJEILsqvtODWyqh0okG7Ts1PNzv8&callback=initMap"
type="text/javascript"></script>
<script>
function initialize() {
var map;
var layer_0;
var layer_1;
var styles = <?php echo $map_styles; ?>;
var map_style = [];
var user_style = styles['<?php echo $map_theme; ?>'];
if (user_style && user_style['style'] != 'undefined') {
map_style = user_style['style'];
}
else {
var default_style = styles['Light Dream'];
if (default_style && default_style['style'] != 'undefined') {
map_style = default_style['style'];
}
}
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>),
zoom: 15,
styles: map_style
});
layer_0 = new google.maps.FusionTablesLayer({
suppressInfoWindows: true,
clickable: false,
query: {
select: "col8",
from: "13zAsmjWdE-uVeVPkr-1qqUQGfZFgPBnBwbNpsWEE"
},
map: map,
styleId: 2,
templateId: 2
});
layer_1 = new google.maps.FusionTablesLayer({
query: {
select: "col2",
from: "1nhy-62Mdybjlipp3_kPrmZb_E4Z7fFjBVhNarqGk"
},
map: map,
styleId: 2,
templateId: 2
});
}
window.onload = initialize;
</script>
Your callback function is "initialize" so put this function in url after api key and also re-create api. and then try it.
EDITED
Was all just about styles because is wrapped into the admin dashboard.
width: 100% didn't work for <div id="mymap">, had to set a fixed width to make it works.
Google map is showing only with wordpress debug mode activated, when switching DEBUG variable to false and refreshing admin page, can't see map anymore, setting it back to true and refreshing page again it appears.
0 errors in chrome's console, clear.
Looks like the map is there already but not visible? If I click over the map is supposed to be, then can see this error in console:
Uncaught ReferenceError: o is not defined
at HTMLDocument.document.addEventListener.t (<anonymous>:1:784)
const t=Object(o.a)(n);if(t)return e.__VUE_DEVTOOLS_CONTEXT_MENU_HAS_TARGET__=!0,void(e.__VUE_DEVTOOLS_CONTEXT_MENU_TARGET__=t)}e.__VUE_DEVTOOLS_CONTEXT_MENU_HAS_TARGET__=null,e.__VUE_DEVTOOLS_CONTEXT_MENU_TARGET__=null})})(window)
Can't understand what's the meaning of this.
wordpress version: 4.9.2
theme: Betheme (Same with storefront or twentyseventeen so discarded theme issue)
scripts loaded by: admin_enqueue_scripts by custom script...
wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxxxxx');
wp_enqueue_script('google-jsapi','https://www.google.com/jsapi');
Full file:
<?
function mostrar_retiradas() {
global $wpdb;
?>
<div class="wrap">
<h2>Retiradas pendientes</h2>
</div>
<?php
// Filtramos la consulta por estado del pedido buscamos wc-retirando
$retirandoids = $wpdb->get_results( "SELECT * FROM `wp_posts` WHERE post_type = 'shop_order' AND post_status = 'wc-retirando' ");
// creamos una copia del pedido llamando a la clase principal
for ($i=0 ; $i<count($retirandoids) ; $i++ ) {
$order_data[$i] = new WC_Order($retirandoids[$i]->ID);
}
// Añadimos todos los campos de direccion del pedido para la consulta de geolocalizacion
for ($i=0 ; $i<count($order_data) ; $i++ ) {
$address[$i] = $order_data[$i]->get_shipping_address_1() . ' ' . $order_data[$i]->get_shipping_address_2() . ' ' . $order_data[$i]->get_shipping_city();
}
for ($i=0 ; $i<count($address) ; $i++ ) {
$direccion[$i] = geocode_address($address[$i]);
}
// if able to geocode the address
for ($i=0 ; $i<count($direccion) ; $i++ ) {
if(($direccion[$i][0]) && ($direccion[$i][1]) && ($direccion[$i][2]) ) {
$latitude[$i] = $direccion[$i][0];
$longitude[$i] = $direccion[$i][1];
$formatted_address[$i] = $direccion[$i][2];
}
}
?>
<!-- google map will be shown here -->
<div id="gmap_canvas">Loading map...</div>
<div id='map-label'>Map shows approximate location.</div>
<!-- JavaScript to show google map -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCEkSTZBVD5tDBrlot1nbRDjIQ103B4xeE"></script>
<!-- <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script> -->
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#gmap_canvas {
height: 100%;
}
</style>
<script type="text/javascript">
var latitudes = <?php echo json_encode($latitude) ?>;
var longitudes = <?php echo json_encode($longitude) ?>;
var direcciones = <?php echo json_encode($formatted_address) ?>;
var markers = [];
for (var i=0; i<latitudes.length ; i++ ) {
var newMarker = {
position: new google.maps.LatLng(latitudes[i], longitudes[i]),
type: 'caution'
}
markers.push(newMarker);
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
},
caution: {
icon: iconBase + 'caution.png'
},
ranger_station: {
icon: iconBase + 'ranger_station.png'
},
truck: {
icon: iconBase + 'truck.png'
}
};
function init_map() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(<?php echo $latitude[0]; ?>, <?php echo $longitude[0]; ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
var marker;
markers.map((item, index) => {
marker = new google.maps.Marker({
position: item.position,
icon: icons[item.type].icon,
map: map
})
infowindow = new google.maps.InfoWindow({
content: direcciones[index]
});
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
})
}
// google.maps.event.addDomListener(window, 'load', init_map);
init_map();
</script>
<?php
}
Any Help to will be much apreciated
Thx in advance.
Could be that the map script is being called after the init_map() function? Also I see that you are calling again the maps script within the function mostrar_retiradas(){, which should only be called once. But in the past I have had issues when using wp_enqueue_script(, they should be called first, and then you should call mostrar_retiradas, I wouldn't recommend having a JavaScript file within a PHP function, the code should be separated from each other.
Looking to disable the Google Map when browsed on a mobile device. Currently running CSS to hide the div if the browser window is 600px or below.
#media only screen and (max-width: 600px) {
.mapCanvas {
display: none;
}
}
How can you disable the JS from querying the Google Maps API if the browser is 600px or smaller?
So that it won't query the API server when the map isn't even displayed.
<div id="mapCanvas"></div>
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the web page
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(50);
// Multiple markers location, latitude, and longitude
var markers = [ <?php echo $js_markers; ?>
];
// Info window content
var infoWindowContent = [ <?php echo $js_content; ?>
];
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Place each marker on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Add info window to marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
}
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(7);
google.maps.event.removeListener(boundsListener);
});
}
// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=???&callback=initMap"></script>
Don't include the google maps API JS file if its mobile
Something like
if (typeof window.orientation !== 'undefined') { ... }
I have a map populating with markers taken from an xml file that are stored in a database. Below the map I am pulling the same info from each marker and displaying them as listings. What I'm trying to to is create a <a href=""> type link that will open the corresponding marker and infowindow beside each listing. Here is my page, it might better explain what I mean: http://poultry.ie/plugin/page/breeders
Here is my code:
<script type="text/javascript">
//<![CDATA[
var redpin = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_red.png',
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var redpinshadow = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
new google.maps.Size(37,32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
function load() {
var gmarkers = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.5076512854544, -7.701416015625),
zoom: 7,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("http://poultry.ie/plugins/CustomPages/pages/phpsqlajax_genxml3.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 phone = markers[i].getAttribute("phone");
var breeds = markers[i].getAttribute("breeds");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b><br />" + address + "<br/>" + phone + "<br/>" + breeds;
var marker = new google.maps.Marker({
map: map,
shadow: redpinshadow,
icon: redpin,
position: point
});
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>
And the php that is dynamically displaying the listings (for this one county):
//Armagh
$data = mysql_query("SELECT * FROM markers WHERE address='Armagh'")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print '<div class="county all armagh">';
Print "<h4>".$info['name'] . "</h4> ";
Print "<em>".$info['address'] . "</em><br /> ";
Print "".$info['phone'] . "<br /> ";
Print 'See on Map<br />';
Print "<em>Breeds:</em> ".$info['breeds'] . "<hr/></div>";
}
The <a href="javascript:myclick( is from a previous attempt at creating this, it doesn't actually have a function at the moment.
I have tried to apply many examples to my code without success as my knowledge of javascript is fairly limited to say the least. My above code might also not be the cleanest as it is my putting together from a lot of examples.
Here is an example (ported from Mike Williams' v2 tutorial) which loads markers from an xml file and has a clickable sidebar
I am setting up a map of different airport locations. My Markers are at the correct locations.
I have been trying to add infowindows but every InfoWindow is showing the same content from the last marker in the array.
How do I fix this so each marker will have its own unique info?
`setMarkers(map, airports);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var airport = locations[i];
var myLatLng = new google.maps.LatLng(airport[1], airport[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
html: airport[3],
});
var contentString =
<?php
$num_rows = (count($locations) - 1);
for($i = 0; $i < count($locations); $i++){
$query = "SELECT * FROM airports WHERE ident='$locations[$i]'";
$result = mysql_query($query, $link)
or die('Error querying database.');
while ($row = mysql_fetch_array($result)) {
if ($i == $num_rows){
echo "'<div id=\"content\">'+";
echo "'<div id=\"siteNotice\">'+";
echo "'</div>'+";
echo "'<b>" . $row['ident'] . "</b></br>'+";
echo "'" . $row['latitude_deg'] . ", " . $row['longitude_deg'] . "' +";
echo "'</div>'+";
echo "'</div>';";
}
}
}
?>
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
//infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
}
You will need to store the data that you need for each infowindow in some sort of array that is accessible by an index number.
The index number is accessed when the user clicks on the marker. The index number is then used to construct the infowindow content on the fly and open the infowindow.
google.maps.event.addListener(marker, 'click', (function(event, index) {
return function(){
infowindow.content = markerArray[index].label + "<br>" + markerArray[index].text;
infowindow.open(map,this);
}
})(marker,i));
Code from: http://srsz750b.appspot.com/api3/polylines-multiple.html