Reputation: 3549
I tryied to use this in my app with ajax, but after it cames problems with inicialization of google maps.
I googled, tried some solution what I found on google and here on stackoverflow, but nothing helped.
Only think I know that there is some probably some proble with initialization of google map sensor caused by ajax.
Ajax without google maps work fine. Google maps example works without ajax also fine. But when I add it in my form which use ajax, problem will occure.
I tried to make testing script to demonstrate the problem which is same as in my original script. All the code and errors are here:
ERRORS from which I see in Chrome tool:
Uncaught ReferenceError: google is not defined
var defaultLatLng = new google.maps.LatLng(50.0926869,14.4231175);
Uncaught TypeError: Cannot read property 'setCenter' of undefined
map.setCenter(defaultLatLng);
address-validator.js
var geocoder, map, marker;
var defaultLatLng = new google.maps.LatLng(50.0926869,14.4231175);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 5,
center: defaultLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(
document.getElementById("map_canvas"),
mapOptions
);
marker = new google.maps.Marker();
}
function validate() {
clearResults();
var address = document.getElementById('address').value;
geocoder.geocode({'address': address }, function(results, status) {
switch(status) {
case google.maps.GeocoderStatus.OK:
document.getElementById('valid').value = 'ANO';
document.getElementById('type').value = results[0].types[0];
document.getElementById('result').value = results[0].formatted_address;
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('long').value = results[0].geometry.location.lng();
mapAddress(results[0]);
break;
case google.maps.GeocoderStatus.ZERO_RESULTS:
document.getElementById('valid').value = 'NE';
break;
default:
alert("An error occured while validating this address")
}
});
}
function clearResults() {
document.getElementById('valid').value = '';
document.getElementById('type').value = '';
document.getElementById('result').value = '';
document.getElementById('lat').value = '';
document.getElementById('long').value = '';
map.setCenter(defaultLatLng);
map.setZoom(0);
marker.setMap(null);
}
function mapAddress(result) {
marker.setPosition(result.geometry.location);
marker.setMap(map);
map.fitBounds(result.geometry.viewport);
}
google.maps.event.addDomListener(window, 'load', initialize);
ajax.js
function ajaxObj( meth, url) {
var x = new XMLHttpRequest();
x.open( meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
main.js
function _(x){
return document.getElementById(x);
}
mapAJAXProblem.js
function emptyElement(x){
_(x).innerHTML = "";
_("status").className = "";
}
function addaction() {
//rid
var a = _("address").value;
var action = _("action").value;
var status = _("status").value;
if(a == "" || action =="") {
_("status").className = "errormessage";
_("status").innerHTML = "Set all form data!";
} else {
_("addbtn").style.display = "none";
_("status").className = "message";
_("status").innerHTML = 'Please wait ...';
var ajax = ajaxObj("POST", "mapAJAXProblem.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "add_success") {
_("status").className = "errormessage";
_("status").innerHTML = ajax.responseText;
_("addbtn").style.display = "block";
} else {
window.alert("OK");
window.location = "mapAJAXProblem.php";
}
}
} //end ajax onready state function
ajax.send("a="+a+"&action="+action);
}
}
mapAJAXProblem.php
<?php
function checkPOST($value) {
if(isset($_POST["$value"]) && !empty($_POST["$value"])) return true;
else return false;
}
if(checkPOST("action") && $_POST["action"] == "addaction") {
$a = $_POST['a'];
$action = preg_replace('#[^a-zA-Z]#', '', $_POST['action']);
if($a == "" || $action == "") {
echo "Set all form data.";
exit();
} else {
//mysql query
echo "add_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script src="js/mapAJAXProblem.js"></script>
<script src="js/address-validator.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<style>
body {
font-family: sans-serif;
}
#address {
width:300px;
height:150px;
float: left;
margin: 10px;
}
#map_canvas {
width:256px;
height:150px;
margin: 10px;
}
#validate {
clear: both;
}
#results {
margin-top: 10px;
}
</style>
</head>
<body>
<header>
</header>
<section>
<form id="form" onsubmit="return false;">
<div>Set address:</div>
<textarea type="text" id="address"></textarea><br />
<!-- <input type="text" id="address" name="address" onfocus="emptyElement('status')" maxlength="255" value="" /> -->
<input type="hidden" name="action" id="action" value="addaction" />
<button id="addbtn" onclick="addaction()">Add</button> <br /> <br />
<div id="status"></div>
</form>
<div id="map_canvas"></div>
<div id="validate"><input type="button" value="Validate" onClick="validate()" /></div>
<div id="results">
<table>
<tr><td align="right">Valid:</td><td><input type="text" id="valid" size="60" /></td></tr>
<tr><td align="right">Type:</td><td><input type="text" id="type" size="60" /></td></tr>
<tr><td align="right">Address:</td><td><input type="text" id="result" size="60" /></td></tr>
<tr><td align="right">lat:</td><td><input type="text" id="lat" size="60" /></td></tr>
<tr><td align="right">long:</td><td><input type="text" id="long" size="60" /><td></tr>
</table>
</div>
</section>
</body>
<footer>
</footer>
</html>
Upvotes: 0
Views: 1447
Reputation: 7069
In your example you'll be needing the Google API. Make sure it gets loaded before address-validator.js
. My advice, keep your libraries in the html <head>
section, move your scripts right before the closing of the </body>
.
In terms of JavaScript you can use an IIFE to help handle loading scripts. No need to declare everything global.
window.ProjectName = (function(google){
var geocoder, map, marker,
defaultLatLng = new google.maps.LatLng(50.0926869,14.4231175);
//... and so on ...
}(window.google));
Upvotes: 1