谷歌地图和ajax问题

时间:2014-04-12 19:57:29

标签: javascript ajax google-maps google-maps-api-3

我试图在我的应用程序中使用this和ajax,但在谷歌地图的官方化出现问题之后。 我用谷歌搜索,尝试了一些解决方案,我在谷歌和这里在stackoverflow上发现,但没有任何帮助。 只是认为我知道由于ajax导致谷歌地图传感器的初始化可能存在一些问题。
没有谷歌地图的Ajax工作正常。谷歌地图示例工作没有ajax也没关系。但是当我在使用ajax的表单中添加它时,会出现问题。

我尝试制作测试脚本来演示与原始脚本相同的问题。所有代码和错误都在这里:

我在Chrome工具中看到的错误
未捕获的ReferenceError:谷歌未定义

var defaultLatLng = new google.maps.LatLng(50.0926869,14.4231175);

未捕获的TypeError:无法读取未定义的属性“setCenter”

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>

1 个答案:

答案 0 :(得分:1)

在您的示例中,您将需要Google API。确保它在address-validator.js之前加载。我的建议是,将您的库放在html <head>部分,在</body>结束之前移动您的脚本。

就JavaScript而言,您可以使用IIFE来帮助处理加载脚本。无需宣布全局。

window.ProjectName = (function(google){
    var geocoder, map, marker,
        defaultLatLng = new google.maps.LatLng(50.0926869,14.4231175);

    //... and so on ...
}(window.google));