I'm getting an issue when I try to load this code, and I can't figure why it doesn't work...
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new google.maps.Geocoder();
$(".textarea-autosize").autosize();
geocoder.geocode({
address: '{$order->address_delivery["address1"]},{$order->address_delivery["postecode"]},{$order->address_delivery["city"]}'
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK)
{
var delivery_map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: results[0].geometry.location
});
var delivery_marker = new google.maps.Marker({
map: delivery_map,
position: results[0].geometry.location,
url: 'http://maps.google.com?q={$order->address_delivery["address1"]},{$order->address_delivery["postcode"]},{$order->address_delivery["city"]}'
});
google.maps.event.addListener(delivery_marker, 'click', function() {
window.open(delivery_marker.url);
});
}
});
});
// Fix wrong maps center when map is hidden
$('#tabAddresses').click(function(){
x = delivery_map.getZoom();
c = delivery_map.getCenter();
google.maps.event.trigger(delivery_map, 'resize');
delivery_map.setZoom(x);
delivery_map.setCenter(c);
});
</script>
The error occurrs on the var geocoder = new google.maps.Geocoder();
Then I tried to load the following script : <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
and I get another error :
'Uncaught TypeError: Cannot read property 'offsetWidth' of null'
Does anyone has any idea of why it doesn't work ?
Google maps aren't loaded at the time when you're trying to call it. You should be using this:
HTML:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initMap" async defer></script>
JS:
function initMap() {
// Google maps are now initialized.
}
You need to include the async and defer attributes into your script - this will make sure that the rest of the website keep loading instead of waiting for the script to load (which is handy, because it's quite big).
Secondly, you pass the "callback" parameter when calling the script. This is the name of the function that should be executed when the script is loaded. This way you can make sure you only initialize the map when it's actually loaded and present within your window.
Simply add this script to your html file:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
If you want to test the google geocoding api or check out some code, check out this link. Google Geocoding Service API Source
Related
Need your help. I have the error on my WordPress site. Google Maps shows this errors:
Jb {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new Jb (https://maps.googleapis.com/m…xALxizYJSGZA470&callback=initMap&ver=4.9.5:157:51"}
And this
Uncaught TypeError: Cannot read property 'firstChild' of null
In my code.js I have this code:
(function ($) {
...
function initMap(officeLocation, pathMap) {
var map = new google.maps.Map(document.getElementById(pathMap), {
zoom: 15,
center: officeLocation
});
var marker = new google.maps.Marker({
position: officeLocation,
map: map
});
}
showOnKyivMap.on('click', function() {
mapCover.fadeIn(500);
initMap(kyivOffice, mapFooter);
});
$(document).ready(function() {
initMap(kyivOffice, mapKyivContacts);
});
})(jQuery);
Google Map script is connected in functions.php
wp_enqueue_script( 'google-maps', "https://maps.googleapis.com/maps/api/js?key=AIzaSyAN-c6nn0xMNJB_2SfGxALxizYJSGZA470&callback=initMap", array("code-js"), '', true);
So what do I do wrong?
Instead of using function to create google map, you can use <iframe> for showing google map. For using <iframe> properly use you can visit to below link:
https://en.support.wordpress.com/google-maps/
I just wondered if anyone knew of a simple script available that will do the following:
Show Google map location of a particular vendor by getting its name from URL. Like we see in various listing websites like Justdial, IndiaMart, Zomato and a lot more. More clearly if my URL is
www.example.com/list.php?city=Delhi
It will show Delhi on google map embed on my list.php web page.
Does anyone know if something like this already exists in PHP?
Thanks in advance.
This will help you.
Html Part.
<div id="map" style="width:100%; height:500px;"></div>
Javascript:
function initMap() {
var latitude = your latitude;
var longitude = Your longitude;
var myLatlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatlng
});
var address = Address;
var infowindow = new google.maps.InfoWindow({
content: address
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click to zoom'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
And finally you have to include map library.
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=Google key&callback=initMap">
</script>
i have a facebook app using Heroku and i use a google map for it. The google map is displayed only in Firefox Browser. Chrome an IE will not display it!
I can't understand why and i need your help!
https://apps.facebook.com/sectorsase/
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script>
function initialize()
{
var IPos=new google.maps.LatLng(4.256,4.568);
var mapProp = {
center:new google.maps.LatLng(44.438683,26.027269),
zoom:13,
disableDefaultUI:true,
draggable: false,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById('googleMap'),mapProp);
var marker=new google.maps.Marker({
position:IPos,
icon:'icn.png'
});
var myCity = new google.maps.Circle({
center:IPos,
radius:3,
strokeColor:'#0000FF',
strokeOpacity:0.8,
strokeWeight:2,
fillColor:'#0000FF',
fillOpacity:0.4
});
myCity.setMap(map);
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.trigger(map, 'resize');
</script>
</head>
<body>
<center><div id='googleMap' style='width:500px;height:380px;'></div></center>
</body>
</html>
IE ERROR:
SEC7111: HTTPS security is compromised by http://maps.google.com/maps/api/js?sensor=false
map.php
SCRIPT1002: Syntax error
map.php, line 17 character 33
CHROME ERROR:
[blocked] The page at https://quiet-everglades-2697.herokuapp.com/map.php ran insecure content from http://maps.google.com/maps/api/js?sensor=false. map.php:1 Uncaught ReferenceError: google is not defined map.php:49
With the errors you've provided, I'm going to assume the page you're viewing is HTTPS. You're loading the Google Maps API from a non-HTTPS source. Just change the script tag to https://maps.google.com/maps/api/js?sensor=false. Or better //maps.google.com/maps/api/js?sensor=false which will automatically fill in the http or https for you.
I'm using jquery ajax to get some results from a php script that is parsing an xml document. After that ajax call i whant to show a map from google api, in a div created by that php script (that's my problem).
Is it possible to load the maps API to the <div id="map-canvas"> that is created in php, after the ajax call??
PHP FILE
... $xmlData = simplexml_load_file("using an http service");
echo "<div id='map-canvas'></div>"; //LOAD MAPP HERE!
echo "<ul>";
foreach($xmlData->StopTimes->StopTime as $stopTime){
echo "<li>",$stopTime->attributes()->Hour,"</li>";
}
echo "</ul>";
}
AJAX FILE
...
//station click, show next stops
$('.station_link').click(function(){
var station_text = $(this).text();
$.ajax({ //make the ajax call
type: "POST", //use POST/GET
url: "../server_side/nextStop.php", //file to send data
data: {poststation : station_text}, //postlink -> php($_POST) value / text -> jquery var value
success: function(data){ //on success, do something
$('#next_stop').html(data);
$('#next_stop').show();
//Google maps API
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
loadScript();
}
});
});
});
This is what i've tried (and much more :p), but i dont even know if its just wrong.
Any help or advise would be appreciated!
-- UPDATE --
As simple as this:
javascript file
//station click, show next stops
$('.station_link').click(function(){
var station_text = $(this).text();
$.ajax({ //make the ajax call
type: "POST", //use POST/GET
url: "../server_side/nextStop.php", //file to send data
data: {poststation : station_text}, //postlink -> php($_POST) value / text -> jquery var value
success: function(data){ //on success, do something
$('#next_stop').html(data);
$('#next_stop').show();
// Google maps API
var mapOptions = {
center: new google.maps.LatLng(37.7831,-122.4039),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
});
});
});
And just adding this <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> to the HTML file.
That's what i whanted, it´s loading the <div id="map-canvas"> as it should.
Ty for help anyway!
Sorry if i didn't proove my point earlier, i'm a bit newbie ;)
Google Maps must be loaded at the time you call center: new google.maps.LatLng(-34.397, 150.644),, so from my opinion you should create a dummy map and initialize it on page load
<div id="dummy"></div>
<script type="text/javascript">
function initGoogle(){
myLatLng = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 1,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById('dummy'), mapOptions);
}
$(document).ready(function(){
var script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'googleMaps';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initGoogle';
document.body.appendChild(script);
});
</script>
<style type="text/css">
#dummy { position: absolute; top: -5000px; left: -5000px; }
</style>
then you can bind whatever you want.
Note: I used jQuery's $(document).ready(), but if you don't use jQuery you can figure it out.
I suspect your initialize isn't getting called due to scope issues as it's only defined in the scope of the Ajax callback and not the global scope, which the Maps SDK will expect.
If you have to load the Google Maps JS asynchronously, use jQuery.getScript() and then initialise your map in getScript's callback.
It could be better though as you're effectively chaining two requests, which is not particularly performant.
You could:
Create a global variable set to 0
Fire off your Ajax call for the Maps div
Use getScript to load the Maps SDK asynchronously and concurrently
In the callback function of your Ajax and getScript calls, increment a global variable you just set
Have a loop that runs every 50ms or so (recursively calling setTimeout, for example), checking the value of the variable you set, waiting until it is equal to 2, set the timeout for another 50ms or so to check again
Once the condition above is satisfied, initialize your map as you know that both the div and maps API have loaded
You can call a js function after AJAX call. You probably better define the function of initialization of gmaps somewhere outside of AJAX call and then after a successful call to your php script call you gmap function (in case of high need with setTimeout('gmap()', 2000); function). But as I see your script it first creates div and then calls function of gmap
I have a webapp that creates markers on a google map and I'm wondering if there is some way to locate place nearby my custom markers so users can see what is around them.
Thank you in advance,
Robert
The Places Libraryapi-doc provides the information you seek. You load the library by adding the libraries=places parameter to the URL that loads the Google Map, as shown here:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false">
</script>
And then you request data about places using code similar to this, copied from the Place Search Requests section of the Developer's Guide, which will search for stores within 500 meters of the point defined in the variable pyrmont:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}