How to calculate route automatically on page load? - php

I have a Google map that I want to automatically load with a prepopulated route (taken from a series of PHP form submissions).
Currently, the PHP forms culminate in a page that has a Google Map on it, and some drop-down boxes with the start and end points prepopulated (from their previous PHP form submissions), and an onChange function on the drop-down menus which calculates the route (onChange="calcRoute();", in the example below). This works fine but, in reality, every final form ends up with just one option for the route. Therefore, getting the user to "select" the start points and end points for the route is worthless - there is only one option in each drop down menus, so I might as well load those options and the calculated route between them automatically when the page loads.
Is there any way of doing this?
My directions function looks like this:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<?PHP
$Start_latLng = $_POST["start-latitude"] . ", " . $_POST["start-longitude"];
$End_latLng = $_POST["end-latitude"] . ", " . $_POST["end-longitude"];
?>
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(54.219218, -2.905669)
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
...and my dropdown menus are populated by the results of the PHP $_POST functions.
Obviously, I need wait for the map to load before I can calculate the route, so a pause might need to be injected - any ideas?

Thank you to #Robot Woods:
Could you just fire calcRoute(); as the last line of your initialize function? – Robot Woods

Related

Leaflet map not filling area

I am using Leaflet to produce different maps on a button click, but the map is not filling the whole area.
The click event grabs various longitudes and latitudes that were stored in my database and sent to the page in a datatable.
The button click looks like this:
$('#datatable').on('click', 'tr > td > a.mapClick', function(e)
{
e.preventDefault();
var rampName = $(this).attr('data-rampname');
var delName = $(this).attr('data-delname');
var actramplat = parseFloat($(this).attr('data-actramplat'));
var actramplng = parseFloat($(this).attr('data-actramplng'));
var actdellat = parseFloat($(this).attr('data-actdellat'));
var actdellng = parseFloat($(this).attr('data-actdellng'));
$('#rampName').val(rampName);
$('#delname').val(delName);
$('#actramplat').val(actramplat);
$('#actramplng').val(actramplng);
$('#actdellat').val(actdellat);
$('#actdellng').val(actdellng);
initMap(rampName, delname, actramplat, actramplng, actdellat, actdellng);
$('#mapModal').modal('show');
});
function initMap(rampName, delname, actramplat, actramplng, actdellat, actdellng)
{
//window.dispatchEvent(new Event('resize')); <-- tried this
//map.invalidateSize(); <-- also tried this
var map = L.map('map').setView([actreclat,actreclng], 8);
L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=zAlHsNvo6jxv4ENZxW3R', {
attribution: '© MapTiler © OpenStreetMap contributors'
}).addTo(map);
}
In my header, I styled the map as follows:
<style>
height:275px;
width:100%;
</style>
In an attempt to prevent a duplicate post, I attempted to use answers from the following post to no avail:
Data-toggle tab does not download Leaflet map
The map continues to NOT fill the whole area.
What adjustments do I need in order to ensure the map fills the whole area?
You're on the right track - the call to invalidateSize() needs to go after the element which contains the map is made visible - which is presumably like this
$('#mapModal').modal('show');
map.invalidateSize();
I added the following modal command and threw the function call inside of it:
$('#datatable').on('click', 'tr > td > a.mapClick', function(e)
{
e.preventDefault();
var rampName = $(this).attr('data-rampname');
var delName = $(this).attr('data-delname');
var actramplat = parseFloat($(this).attr('data-actramplat'));
var actramplng = parseFloat($(this).attr('data-actramplng'));
var actdellat = parseFloat($(this).attr('data-actdellat'));
var actdellng = parseFloat($(this).attr('data-actdellng'));
$('#rampName').val(rampName);
$('#delname').val(delName);
$('#actramplat').val(actramplat);
$('#actramplng').val(actramplng);
$('#actdellat').val(actdellat);
$('#actdellng').val(actdellng);
$('#mapModal').modal('show');
// added below modal function
$("#actionMatchbackModal").on("shown.bs.modal", function () {
initMap(rampName, delname, actramplat, actramplng, actdellat, actdellng);
});
});
Then, inside the actual function, I added the map.invalidateSize() after the creation of the map variable:
function initMap(rampName, delname, actramplat, actramplng, actdellat, actdellng)
{
var map = L.map('map').setView([actreclat,actreclng], 8);
map.invalidateSize();
L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=zAlHsNvo6jxv4ENZxW3R', {
attribution: '© MapTiler © OpenStreetMap contributors'
}).addTo(map);
}
Now the map fills the whole area.

Load google maps to div loaded by ajax

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

Updating Google Map Marker

I'm trying to make a Google map that updates a marker as a user's location is updated. I have most of it done, but I'm having one small issue. I want one marker that shows the starting point, which I have working, but the second point should keep moving, and it should allow multiple users to be tracked at once.
I can get this to work for one user (sending GPS coordinates from Android app). It will set the start marker, and as their location changes the marker will move to reflect that. My problems occur when I start tracking a second user. The current position marker for the first user becomes the starting location for the second user. It 'jumps' from the first path to the other (see picture). I know this is partly due to the declaration of the 'marker1' variable at the top, but I've tried many things with no luck. I need to be able to create as many as I need for n number of users so I can't declare a bunch of variables for each one.
You can see in the picture what is happening. This is the moment when a new user triggers the tracking function in the app. Before this second user activates the tracking function, the marker for the first user was moving properly.
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var loc = {};
var mark = {};
var markers = {};
var marker1;
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var user_id = data[0];
var lati = data[1]; //get id
var longi = data[2]; //get name
var myLatlngt = new google.maps.LatLng(lati, longi);
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
//if (typeof markers[user_id] === 'undefined') {
//markers[user_id] = [];
//}
if (typeof mark[user_id] === 'undefined') {
mark[user_id] = myLatlngt;
}
loc[user_id].push(myLatlngt);
//markers[user_id].push(myLatlngt);
var x;
for (x in loc) {
var polyline = new google.maps.Polyline({
map: map,
path: loc[x],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
///location variables
var start_loc = loc[user_id];
var start_marker = start_loc[0]; //start location of given user
var current_loc = start_loc[start_loc.length -1]; //last known location of given user
//set the start marker
var marker = new google.maps.Marker({
position: start_marker,
title: user_id
});
marker.setMap(map);
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
else {
marker1 = new google.maps.Marker({
position: current_loc,
map: map
});
}
}
//console.log('location :::', x);
console.log('Marker: ', mark);
}
});
}, 1000);
});
});
}
Considering that I don't really know javascript I may be totaly wrong here, but I am assuming that the anonymous function sent as argument to setInterval is called multiple times (?).
If that is the case, I would expect marker1 to be reused since it is declared outside of the function, I.e, it is the same marker1 used for every function call in this part of the code
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
I guess you could use the same method for the marker1 as you did for the loc, having it as an array indexed by the user ID. (perhaps calling it currentLocationMarker would be a better name too)
Another way would be to have the marker1 only existing within the function, but that may cause all the previous current location markers for a user to be visible. Not sure about that, I do not get the full picture of this system you are building.
It's not totally clear what the issue is, but have you tried using .panTo()? It scrolls smoothly to a new location. Call it after your .setPosition().
if (marker1 != null) {
marker1.setPosition(current_loc);
map.panTo( current_loc );
}

Google Maps load issues on PHP page

I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian
Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.
It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}
You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);

Problem with loading google map v3 asynchronously

My current solution for loading Google map scripts, is the old fashion way.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
But this takes to long and rendering content is delayed. Then I looked at the Google Map Documentation and discovered how one can load the Goole Map javascripts asynchronously.
So I tested this in the javascript I'm already using. This is just snippets of my script.
jQuery(document).ready(function() {
googleMaploadScript();
someFunction();
}
// Script for loading googlemap with callback to initialize Google map
function googleMaploadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=true&callback=initGoogleMap";
document.body.appendChild(script);
}
// Some function that calls populateGeoMap()
function someFunction() {
(...)
populateGeoMap();
}
// Script for populating google map with locations
function populateGeoMap() {
// This is where I initialized google map each time I load the page using google map
// But since I'm using a callback, I've commented this out.
//initGoogleMap();
var lat = '12.142123';
var lng = '54.524522';
latLng = new google.maps.LatLng(lat,lng); <-- THIS FAILS
}
// Google map init
function initGoogleMap() {
alert('test'); <-- THIS ALERT IS NEVER TRIGGERED
options = {zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById("map_canvas"), options);
geocoder = new google.maps.Geocoder();
icon = new google.maps.MarkerImage("http://mysite.com/img/pin_red.png", null, null, null, new google.maps.Size(32, 32));
bounds = new google.maps.LatLngBounds();
}
My script fails at new google.maps.LatLng(lat,lng); and this is because initGoogleMap() has not been run.
It seems that the callback in the script.src did not work - because my alert is never fired. Or it might be because things are not laoded in the correct order, but still, the alert should have been triggered.
Does anyone have experience with this?
I had the same problem and worked it out like this:
the problem is the fact that you can't get to the jQuery object itself from outside jQuery.
the API callback attribute at the end has only access to the global javascript. read up opn javascript namespace to understand better.
my solution is to set up a global object outside of the $document.ready(function(){...
var global = {};
next, you write the init function inside your jQuery block for the map as a variable and attach it to the global object:
global.initMap = function(){ ...}
now you can reference your jquery function as a global variable in the url query string like this:
...&callback=global.initMap
this worked for me.
tim's suggestion is excellent!
This is working asynchronous (lazy loading) of google maps v3 script with jQuery based Google Maps plugins.
This way no script except head.js+jquery.js are blocking the page and google maps starts loading as soon as is possible.
window.load should be accessed quickly. tested on ffox 12, ie7,8,9 and chrome 18.
due to some issues with ie7,8 it was not possible to load jquery.js asynchronously :/
//////////////////// lazy loaded google map
// load head.js normally before this code.
// due to IE7,8 or head.js bug you HAVE TO load normally jQuery too:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="/PATH/head.js"></script>
// load rest of your javascript using head.js function
head.js("yourscripts.js");
// IMPORTANT: google map plugin must be tagged like this:
head.js({gmap:"YOUR_PATHs/jquery.mapka.v3-rc.js"});
var global = {};
global.googlemaps_init = function(){
head.ready("gmap", function() {
// jquery-ui-map v3 init of google maps (place YOUR jQuery based google maps plugin init here)
$('#map_canvas').gmap({ 'center': '42.345573,-71.098326' });
}); // head.gmap.ready END
} // global.googlemaps_init END
function loadGmapScript() {
var global = {};
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?&sensor=false&callback=global.googlemaps_init";
document.body.appendChild(script);
}
window.onload = loadGmapScript;
//////////////////// lazy loaded google map END
This is because you're trying to initialize an object that you don't have access to. Try moving the GA functions into the document.onready block:
$(function(){
// Script for loading googlemap with callback to initialize Google map
function googleMaploadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=true&callback=initGoogleMap";
document.body.appendChild(script);
}
// Some function that calls populateGeoMap()
function someFunction() {
(...)
populateGeoMap();
}
// Script for populating google map with locations
function populateGeoMap() {
// This is where I initialized google map each time I load the page using google map
// But since I'm using a callback, I've commented this out.
//initGoogleMap();
var lat = '12.142123';
var lng = '54.524522';
latLng = new google.maps.LatLng(lat,lng); <-- THIS FAILS
}
// Google map init
function initGoogleMap() {
alert('test'); <-- THIS ALERT IS NEVER TRIGGERED
options = {zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById("map_canvas"), options);
geocoder = new google.maps.Geocoder();
icon = new google.maps.MarkerImage("http://mysite.com/img/pin_red.png", null, null, null, new google.maps.Size(32, 32));
bounds = new google.maps.LatLngBounds();
}
googleMaploadScript();
someFunction();
});
I think what happens is that you actually trigger "somefunction" before the map is loaded so JS fails and never actually executes the "initGoogleMap".
Place your somefunction at the end of the initGoogleMap like that:
google.maps.event.addListener(map, 'loaded', function(){
somefunction();
});
K
you can use the async mode when loading Google Maps api, you need to provide a callback function:
http://maps.googleapis.com/maps/api/js?sensor=true&callback=my_callback_function
Here http://lucamanzo-soluzione-software.it/wp/?p=5 you can find a simple jquery plugin showing all the steps to use the async loading and jquery, and building a map with just a few lines of code. Usage example:
$.gmapstools.init();
$("#my_map_canvas").gmap({lat:37.4221913, lng:-122.08458530000001, draw_marker:true, zoom_level:13});

Categories