douzhuang2016 2014-08-14 10:20
浏览 65
已采纳

使用GMap API和Ajax对最近的商店进行地理标记

is there anyone can help please ? :)

1) First I get the user coords with geoloc function 2) I compare these coords to database shops to find the nearest and get shop coords 3) I want to show the Google Map with the pin in the middle

But I get too much recursion error, and wonder how to set ajax return because if I directly add positionmagasin = new google.maps.LatLng(45.764043,4.835659); instead of positionmagasin = new google.maps.LatLng(coordonnees); it works well...

Thank you for your answer !

Here my html and Script :

    <!-- Un élément HTML pour recueillir l’affichage -->
    <div id="infoposition"></div>

    <div id="map"></div>

    <script type="text/javascript">
        // Récupère tous les coordonnées des magasins
        function getMarkers(map) {
            var magasins = new Array;
            <?php 
                $querymag = mysql_query("SELECT * FROM magasins");
                $nbmag = mysql_num_rows($querymag);
                if($nbmag > 0){
                    while($rowmag = mysql_fetch_array($querymag)){
                        $mag_id = $rowmag['id_magasins'];
                        $mag_titre = $rowmag['titre_magasins'];
                        $mag_lat = $rowmag['lat_magasins'];
                        $mag_lng = $rowmag['lng_magasins'];
                    ?>
                        var intermediaire = new Array('<?php echo $mag_id;?>','<?php echo $mag_titre;?>','<?php echo $mag_lat;?>','<?php echo $mag_lng;?>');
                        magasins.push(intermediaire);
                    <?php 
                    }
                }
            ?>
            setMarkers(map, magasins);
        }

        // Place les markers sur la carte
        function setMarkers(map, locations) {
            for (var i = 0; i < locations.length; i++) {
                var magasins = locations[i];
                //console.log(magasins);
                var myLatLng = new google.maps.LatLng(magasins[2], magasins[3]);
                var infoWindow = new google.maps.InfoWindow();
                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    animation: google.maps.Animation.DROP,
                });
                (function(i) {
                    google.maps.event.addListener(marker, "click", function() {
                        var magasins = locations[i];
                        infoWindow.close();
                        infoWindow.setContent(
                            "<div id='boxcontent' style='font-family:Calibri'><strong style='color:green'>"
                            + magasins[1] +
                            "</strong><br /><span style='font-size:12px;color:#333'>Ceci est un test.</span></div>"
                        );
                        infoWindow.open(map, this);
                    });
                })(i);
            }
        }

        function maPosition(position) {
            // Récupère les coordonnées de l'utilisateur
            var x = position.coords.latitude;
            var y = position.coords.longitude;

            // Lance la fonction de calcul SQL pour trouver les coordonnées du magasin le + proche
            var request = $.ajax({
                url: 'fichier2.php',
                type: 'GET',
                data: { 
                    action: 'position',
                    lat: x,
                    lng: y
                }
            });

            request.done(function(retourAjax){
                //donne les coordonnées du magasin en paramètre
                document.getElementById("infoposition").innerHTML = retourAjax;
                var coordonnees = retourAjax;
                //---------------- là ça bloque !!! ------------------ //
                positionmagasin = new google.maps.LatLng(coordonnees);
                // --------------------------------------------------- //

                map = new google.maps.Map(document.getElementById("map"), {
                    zoom: 7,
                    center: positionmagasin,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                });

                //centre la carte sur la position du magasin
                map.panTo(positionmagasin);
                getMarkers(map);
            });

            request.fail(function(retourAjax) {
                defPosition();
            });
        }

        // Affichage de la position par défaut en cas d'erreur
        function defPosition() {
            var info = "Erreur lors de la géolocalisation : Affichage par défaut";
            document.getElementById("infoposition").innerHTML = info;

            var latlng = new google.maps.LatLng(48.856614,2.352222);

            map = new google.maps.Map(document.getElementById("map"), {
                zoom: 7,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            map.panTo(latlng);
            getMarkers(map);
        }

        // Fonction de callback en cas d’erreur
        function erreurPosition(error) {
            var info = "Erreur lors de la géolocalisation : ";
            switch(error.code) {
            case error.TIMEOUT:
                info += "Timeout !";
            break;
            case error.PERMISSION_DENIED:
                info += "Vous n’avez pas donné la permission // affichage de la position par défaut";
                defPosition();
            break;
            case error.POSITION_UNAVAILABLE:
                info += "La position n’a pu être déterminée";
                defPosition();
            break;
            case error.UNKNOWN_ERROR:
            info += "Erreur inconnue";
            break;
            }
            document.getElementById("infoposition").innerHTML = info;
        }

        // Tester si le navigateur est compatible et lancer la géolocalisation
        if(navigator.geolocation) {
            survId = navigator.geolocation.getCurrentPosition(maPosition,erreurPosition);
        } else {
            alert("Ce navigateur ne supporte pas la géolocalisation");
        }
    </script>

The PHP :

<?php
include 'fonction/_connexion.php';

function Findmagasin($lat1, $lng1){
    $query = mysql_query("SELECT *, get_distance_metres($lat1, $lng1, lat_magasins, lng_magasins) AS proximite 
          FROM magasins WHERE get_distance_metres($lat1, $lng1, lat_magasins, lng_magasins) < 1000000 ORDER BY proximite ASC LIMIT 1");
        $nb = mysql_num_rows($query);
        if($nb = 1){
            $row = mysql_fetch_array($query);
            $id = $row['id_magasins'];
            $titre = $row['titre_magasins'];
            $x = $row['lat_magasins'];
            $y = $row['lng_magasins'];
            // coordonnées du magasin le plus proche

            echo $x.",".$y;
        } else {
            echo "48.856614,2.352222";
        }
}

// vérifier si une action à réaliser est transmise
if (isset($_GET['action'])) {

    // si oui réalise l'action
    $action = $_GET['action'];

    switch ($action) {
        case 'position':

            // verifie qu'un étudiant a bien été transmis
            if (isset($_GET['lat']) && isset($_GET['lng'])){
                $lat1 = $_GET['lat'];
                $lng1 = $_GET['lng'];
                Findmagasin($lat1, $lng1);
            } else {
                echo 'aucun ordre transmis';
            }
            break;
    }

} else {
    echo 'aucune action transmise';
} ?>
  • 写回答

1条回答 默认 最新

  • dqoys62082 2014-08-14 12:12
    关注

    You wrote:

    But I get too much recursion error, ... because if I directly add positionmagasin = new google.maps.LatLng(45.764043,4.835659); instead of positionmagasin = new google.maps.LatLng(coordonnees); it works well...

    The google.maps.LatLng constructor takes 2 numbers as arguments, not a single argument.

    If coordonnees is an array, do this;

    positionmagasin = new google.maps.LatLng(coordonnees[0],coordonnees[1]);
    

    If coordonnees is a comma separated string containing two numeric values, do this:

    var coords = coordonnees.split(",");
    positionmagasin = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统