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.
Trying to retain the social share counts after migrating http to https and revert our social proof. I am looking for help from folks who can advise on how to summarize two functions and output the total number of shares in the DIV:
<div id="pin-div">0</div>
The function returns the count of HTTP url:
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(function() {
var url = "<?php $page_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $page_url; ?>";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
Same code returns the count of HTTPS url:
<script type="text/javascript">
$(function() {
var url = "<?php $page_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $page_url; ?>";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
What am I missing to sum both results?
Thank you all JS developers and hope this will help thousands of people!
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.
I'm really confused about this. I'm using Cincopa to create and embed image galleries onto my Meteor site.
This works. The gallery shows up on page load.:
<template name="test">
<!-- Image Gallery Embed Code -->_
<div id="cp_widget_a718e3a7-4a35-4f13-b14e-299cc73c6ecb">...</div>
<script type="text/javascript">
var cpo = [];
cpo["_object"] = "cp_widget_a718e3a7-4a35-4f13-b14e-299cc73c6ecb";
cpo["_fid"] = "A4IAkTttPOWL";
var _cpmp = _cpmp || [];
_cpmp.push(cpo);
(function() {
var cp = document.createElement("script");
cp.type = "text/javascript";
cp.async = true;
cp.src = "//www.cincopa.com/media-platform/runtime/libasync.js";
var c = document.getElementsByTagName("script")[0];
c.parentNode.insertBefore(cp, c);
})();
</script>
<!-- Image Gallery Embed Code -->_
</template>
This does not. Nothing but the empty <div> with ... shows up. There are no error messages.
<template name="test">
<div id="cp_widget_a718e3a7-4a35-4f13-b14e-299cc73c6ecb">...</div>
</template>
JS:
Template.test.onRendered(function(){
var cpo = [];
cpo["_object"] = "cp_widget_a718e3a7-4a35-4f13-b14e-299cc73c6ecb";
cpo["_fid"] = "A4IAkTttPOWL";
var _cpmp = _cpmp || [];
_cpmp.push(cpo);
(function() {
var cp = document.createElement("script");
cp.type = "text/javascript";
cp.async = true;
cp.src = "//www.cincopa.com/media-platform/runtime/libasync.js";
var c = document.getElementsByTagName("script")[0];
c.parentNode.insertBefore(cp, c);
})();
});
It's the exact same code...
Am I missing something with how Meteor loads things?
EDIT
You need to make those variables available in the global scope for the script to access them:
Change
var _cpmp = _cpmp || [];
Remove the 'var' keyword and use window instead
window._cpmp = window._cpmp || [];
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>