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.
Related
I have a PHP Site which takes Data from XML File to display Markers on a Google Maps. When I navigate direct to the page, everything is working. To integrate that code on my Wordpress Page, I thought about writing a plugin for that:
<? defined('ABSPATH') or die("Thanks for visting");
function showMap() { ?>
<style>
/* 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;
}
</style>
<div id="map"></div>
<script>
var customLabel = {
Location: {
label: 'L'
},
Brautaustatter: {
label: 'B'
},
Herrenausstatter: {
label: 'H'
},
Florist: {
label: 'F'
},
Konditor: {
label: 'K'
},
Sonstiges: {
label: 'S'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(48.2048, 16.375),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('showXML.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('location');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
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>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
<? add_shortcode( 'show_google_maps', 'showMap' ); ?>
<? } ?>
Now I do not know how to return the whole map with the markers? How can I solve this? Do I have to create a "main" function where all the other functions are nested? Is that what I want to achieve possible with that piece of code? Thanks for any advice!
BR,
Stefan
I need to create a new choropleth version of this map whereby the polygons' colorFills respond to data in a column ("PERCENTAGE") from a table that I merged with the original fusion table. The polygons will be either green, yellow or red depending on the percentages.
I'm working from a wordpress plugin that was built by someone else for a project.
var map;
function initMap() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng( 51.41467424448992, 16.737563625000007 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// initialize the map
map = new google.maps.Map( document.getElementById( 'map-canvas' ),
myOptions );
// google maps styles go below here...
map.setOptions( { styles: styles } );
// Initialize JSONP request
var script = document.createElement( 'script' );
var url = ['https://www.googleapis.com/fusiontables/v2/query?'];
url.push( 'sql=' );
var query = 'SELECT name, iso_a2, kml_4326 FROM ' +
'1_XPSB5N6EOCr5i9etLrR0HA3717jfyk4iOamXWqu';
var encodedQuery = encodeURIComponent( query );
url.push( encodedQuery );
url.push( '&callback=drawMap' );
url.push( '&key=AIzaSyAm9yWCV7JPCTHCJut8whOjARd7pwROFDQ' );
script.src = url.join( '' );
var body = document.getElementsByTagName( 'body' )[0];
body.appendChild( script );
}
function drawMap( data ) {
//console.log(getCountry);
//console.log(data['rows']);
var rows = data['rows'];
for ( var i in rows ) {
if ( rows[i][0] != 'Antarctica' ) {
var newCoordinates = [];
var geometries = rows[i][2]['geometries'];
if ( geometries ) {
for ( var j in geometries ) {
newCoordinates.push( constructNewCoordinates( geometries[j] ) );
}
} else {
newCoordinates = constructNewCoordinates( rows[i][2]['geometry'] );
}
var fillColor = "#fff";
var strokeColor = "transparent";//#333 ()
if ( getCountry[rows[i][1]] ) {
fillColor = "#fbbd2b";
strokeColor = "#ff9900";
}
var country = new google.maps.Polygon( {
paths: newCoordinates,
strokeColor: strokeColor,
strokeOpacity: 1,
strokeWeight: 0.4,
fillColor: fillColor,
fillOpacity: 0.18,
name: getCountry[rows[i][1]],
nameCode: rows[i][1]
} );
if ( getCountry[rows[i][1]] ) {
google.maps.event.addListener( country, 'mouseover', function () {
this.setOptions( { fillOpacity: 0.4 } );
} );
google.maps.event.addListener( country, 'mouseout', function () {
this.setOptions( { fillOpacity: 0.18 } );
} );
google.maps.event.addListener( country, 'click', function () {
GetCounty( this.nameCode ); console.log(this.nameCode);
} );
}
google.maps.Polygon.prototype.my_getBounds = function () {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach( function ( element, index ) {
bounds.extend( element );
} );
return bounds;
};
var lat = country.my_getBounds().getCenter().lat();
var lng = country.my_getBounds().getCenter().lng();
country.setMap( map );
}
}
}
function constructNewCoordinates( polygon ) {
var newCoordinates = [];
var coordinates = polygon['coordinates'][0];
for ( var i in coordinates ) {
newCoordinates.push(
new google.maps.LatLng( coordinates[i][1], coordinates[i][0] ) );
}
return newCoordinates;
}
// Search form, contentpop code goes below here
I have tried adding the styles to the 'new google.maps.Polygon' variable (as below) but it didn't work so I'm wondering where I'm going wrong. Any suggestions appreciated.
{
where: 'PERCENTAGE < 33.3%',
polygonOptions: {
fillColor: '#0000FF'
}
Try 'PERCENTAGE < 0.33' instead. The column is formatted as a percentage, but the actual value is a plain number. You can see this if you add a filter on that column.
So, I'm still not sure why I couldn't get it working inside "var country new google.maps.Polygon" but managed it with "var layer = new google.maps.FusionTablesLayer"
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'iso_a2',
from: '1_XPSB5N6EOCr5i9etLrR0HA3717jfyk4iOamXWqu'
},
styles: [{
where: 'PERCENTAGE < 33.3',
polygonOptions: {
fillColor: "#92bf24",
strokeColor: "#ff9900",
}
}]
});
layer.setMap(map);
There will be 4 different maps in the dropdown though, so I might see if I can find a more convenient way to style the polygons - maybe from the SQL table, which is uncharted territory for me.
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 am using Gridstack with Knockout.js. I am using http://troolee.github.io/gridstack.js/demo/knockout.html to create Gridstack widgets. I added a Google map in one of these widgets. The map appears with a scroll bar. Also, I need to have some kind of heading, as it is in its present state. The main problem is that the dimension of the map is fixed and when I resize the widget, the map does not fit in the widget automatically. Here is my full code:
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
var ViewModel = function (controller, componentInfo) {
var grid = null;
this.widgets = controller.widgets;
this.id = controller.id;
this.afterAddWidget = function (items) {
if (grid == null) {
grid = $(componentInfo.element).find('.grid-stack').gridstack({
auto: false,
animate: true
}).data('gridstack');
}
var item = _.find(items, function (i) { return i.nodeType == 1 });
grid.addWidget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.removeWidget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item-content" >',
' <header style="background-color: green;"> ',
' <button data-bind="click: $root.deleteWidget">Delete me</button><br>',
' <label><strong data-bind="text: $root.ids"></strong></label>',
' </header>',
' <div data-bind="attr: {id: $root.ids}">',
' </div>',
' </div>',
' </div>',
'</div> '
].join('')
});
$(function () {
var ids;
var Controller = function () {
var self = this;
this.widgets = ko.observableArray([]);
this.id = ko.observable("google-map");
this.ids = "";
this.addNewWidget = function () {
this.ids = this.id(); // this.ids is used to give id to div elements
this.widgets.push({
x: 0,
y: 0,
width:4,
height:5,
auto_position: true,
});
// calling method to draw map
createWidget(this.ids);
return false;
};
this.deleteWidget = function (item) {
self.widgets.remove(item);
return false;
};
};
ko.applyBindings(new Controller());
});
function createWidget(id) {
var dataArray, latitude, longitude, speed;
// Load the Visualization API and the corechart package.
try {
google.charts.load('current', {'packages':['map', 'gauge']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
}
catch ( err ) {
//console.log(err);
}
function drawChart() {
latitude = Number(12.93213);
longitude = Number(77.695185);
var mapOptions = {
showTooltip: true,
showInfoWindow: true,
zoomLevel: 16, // range: 0-21 for "roadmap" map type
mapType: 'roadmap',
enableScrollWheel: true,
draggable: false,
};
var coordinates = "Latitude : " + latitude + "\nLongitude : "+ longitude;
var mapData = google.visualization.arrayToDataTable([
['Lat', 'Long', 'Name'],
[latitude, longitude, coordinates]
] );
try {
//var chart = new google.visualization.Gauge(document.getElementById('gauge'));
var map = new google.visualization.Map(document.getElementById(id));
map.draw(mapData, mapOptions);
}
catch (err) {
console.log(err);
}
} // drawChart() ends here
} // createWidgets() ends here
If you use Google Maps API v3.16 and later, polyline are not drawn when a new marker is added to the polyline path and MVCArray, only markers plotted on a map.
My program based on code from http://nettique.free.fr/gmap/toolbar.html
html file :
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>map toolbar implementation</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.exp&sensor=true"></script>
<style type="text/css">
--- truncate ----
</style>
<script type="text/javascript" src="toolbarv3_files/mapToolbar.js"></script>
<script type="text/javascript">
// Register an event listener to fire when the page finishes loading.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
body section
drawing toolbar :
<div id="hand_b" onclick="MapToolbar.stopEditing()"/>
<div id="line_b" onclick="MapToolbar.initFeature('line')"/>
canvas :
<div id="map" style="width: 85%; height: 100%; position: absolute;"></div>
script file (mapToolbar.js):
var map;
var MapToolbar = {
//reorder index of a poly markers array
reindex:function(markers){
markers.forEach(function(marker, index){
marker.index = index;
});
},
//add a point to a poly, 'e' can be a click event or a latLng object
addPoint : function(e, poly, index) {
var e = (typeof e.latLng != "undefined")? e.latLng : e,
image = new google.maps.MarkerImage('images/marker-edition.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
imageover = new google.maps.MarkerImage('images/marker-edition-over.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
path = poly.getPath(),
index = (typeof index != "undefined")? index : path.length,
markers = (poly.markers)? poly.markers : new google.maps.MVCArray,
marker = new google.maps.Marker({
position: e,
map: map,
draggable: true,
icon: image
});
marker.index = index;
path.insertAt(index, e);
markers.insertAt(index, marker)
if(arguments[2]){
MapToolbar.reindex(markers);
}
features:{
.....
lineTab: {},
.....
},
//instanciate a new Feature instance and create a reference
initFeature: function(type){
new MapToolbar.Feature(type);
},
//check if a toolbar button is selected
isSelected: function(el){
return (el.className == "selected");
},
//the map DOM node container
....
lineCounter:0,
....
//select hand button
stopEditing: function() {
this.removeClickEvent();
this.select("hand_b");
},
//create new polyline function
MapToolbar.Feature.prototype.poly = function(type) {
var color = MapToolbar.getColor(false),
path = new google.maps.MVCArray,
poly,
self = this,
el = type + "_b";
if(type=="shape"){
poly = self.createShape( {strokeWeight: 3, fillColor: color}, path );
}else if(type=="line"){
poly = self.createLine( {strokeWeight: 3, strokeColor: color }, path );
}
poly.markers = new google.maps.MVCArray;
if(MapToolbar.isSelected(document.getElementById(el))) return;
MapToolbar.select(el);
MapToolbar.currentFeature = poly;
poly.setMap(map);
if(!poly.$el){
++MapToolbar[type+"Counter"];
poly.id = type + '_'+ MapToolbar[type+"Counter"];
poly.$el = MapToolbar.addFeatureEntry(poly.id, color);
MapToolbar.features[type+"Tab"][poly.id] = poly;
}
}
MapToolbar.Feature.prototype.createLine = function(opts, path) {
var poly = new google.maps.Polyline({
strokeWeight: opts.strokeWeight,
strokeColor: opts.strokeColor
}), self = this;
poly.setPath(new google.maps.MVCArray(path));
return poly;
}
//initialization function
function initialize(container) {
var options = {
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
map = new google.maps.Map(document.getElementById('map'));
map.setCenter(new google.maps.LatLng(47.9, 1.9 ));
map.setZoom(12);
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
with(MapToolbar){
with(buttons){
.....
$hand = document.getElementById("hand_b");
$line = document.getElementById("line_b");
....
}
....
select("hand_b");
}
MapToolbar.polyClickEvent = google.maps.event.addListener(map, 'click', function(event){
if( !MapToolbar.isSelected(MapToolbar.buttons.$shape) && !MapToolbar.isSelected(MapToolbar.buttons.$line) ) return;
if(MapToolbar.currentFeature){
MapToolbar.addPoint(event, MapToolbar.currentFeature);
}
});
}
complete version of "mapToolbar.js" script file is also available at : https://code.google.com/p/js2shapefile/source/browse/trunk/lib/mapToolbar.js?r=2
an error occurred when executing line "path.insertAt(index, e);" (addPoint function).
TypeError: this.j[qd] is not a function
...his[gd](a,b)}};L.insertAt=function(a,b){this.j[qd](a,0,b);bg(this);S[n](this,"in...
{main,g...try}.js (line 26, col 1473)
I had the same problem. I've solved changing poly.setPath in createLine function.
MapToolbar.Feature.prototype.createLine = function(opts, path) {
var poly = new google.maps.Polyline({
strokeWeight: opts.strokeWeight,
strokeColor: opts.strokeColor
}), self = this;
// 27/08/2014 - This not work
//poly.setPath(new google.maps.MVCArray(path));
poly.setPath(path);
return poly;
}