douzi2749 2013-12-02 22:33
浏览 44

谷歌地图代码标记代码适用于Firefox,但不适用于chrome或safari

I am creating a user map system that allows users to either select a new location or select a saved location (from an sql file). I want the map to load with a draggable marker that can be used to select a new position, with the lat/lng populating the relevant fields on the form. I also want the saved locations to populate a dropdown menu, allowing the users to select a location, the lat/lng and name will then populate the relevant fields and the draggable marker disappears from the map. When ‘Select a new location’ is selected from the dropdown menu, the ‘saved locations’ markers disappear and the draggable marker should reappear.

This is the code I have. I admit I am new to this, and have used the Google Maps Developer a lot, as well as searching online and have taken quite a while to get to this point. This code does exactly what I want in Firefox and IE, but not in Chrome or Safari. In Chrome the saved locations appear in the dropdown menu but when I click on ‘select a new location’ after I have loaded a saved location, the draggable marker does not reappear. In Safari, the saved locations are not even loaded. I would appreciate any advice on how I can fix the errors with my code that could be causing this. I have tried debugging in Chrome (31.0.1650.57 ) and Safari (5.1.7 for windows), I get Cannot read property '_e3' of undefined of the main.js and also Unexpected token < error404.000webhost.com/ (I’m hosting the site on 000webhost).

This is my html code:

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <title>Sightings Form Member</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="js/main.js"></script>
    <script src="js/ajax.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">

    var map;
    var markers = [];
    var markerNew;
    var infoWindow;
    var infowindow;
    var locationSelect;
    var geocoder = new google.maps.Geocoder();
    var imageNew = 'binoculars3.png';
    var imageSave = 'star-3a.png';

    function geocodePosition(pos) {
        geocoder.geocode({
        latLng: pos
        }, function(responses) {
            if (responses && responses.length > 0) {
                console.log(responses);
                updateMarkerAddress(responses[0].address_components[0].long_name);
                } else {
                updateMarkerAddress('Cannot determine address at this location.');
                }
            });
    }

    function updateMarkerPosition(latLng) {
        var MapLat =latLng.lat();
        var MapLng =latLng.lng();  
            document.getElementById('latitude').value = MapLat;
            document.getElementById('longitude').value = MapLng;
    }

    function updateMarkerAddress(str) {
        document.getElementById('address').innerHTML = str;
          infowindow.open(map, markerNew);
          infowindow.setContent(address);
    }

    function initialize() {
        var latLng = new google.maps.LatLng(10.6667, -61.3152);
            map = new google.maps.Map(document.getElementById("map"), {
            center: latLng,
            zoom: 8,
            mapTypeId: 'hybrid',
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
                panControl: true,
                panControlOptions: {
                position: google.maps.ControlPosition.TOP_RIGHT
            },
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.LARGE,
                    position: google.maps.ControlPosition.TOP_left
                }
   });

   infoWindow = new google.maps.InfoWindow();

   NewMarker(latLng);
   infowindow = new google.maps.InfoWindow();
   infowindow.setContent(address);

    // Adds saved locations //Set up dropdown options 
    locationSelect = document.getElementById("locationSelect");
    locationSelect.onchange = function() {
        var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
        if (markerNum != "none"){
            google.maps.event.trigger(markers[markerNum], 'click');
            }  
    };

   //Read in saved locations
    downloadUrl('RetrieveSavedLoc.php', function(data) {
       var xml =   parseXml(data);
       var markerNodes = xml.documentElement.getElementsByTagName("markerSave");
       var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < markerNodes.length; i++) {
                var name = markerNodes[i].getAttribute("loc_name");
                var address = markerNodes[i].getAttribute("dayyear");
                var savedlatlng = new google.maps.LatLng(
                    parseFloat(markerNodes[i].getAttribute("lat")),
                    parseFloat(markerNodes[i].getAttribute("lng")));
                var MapLat = markerNodes[i].getAttribute("lat");
                var MapLon = markerNodes[i].getAttribute("lng");

        createOption(name, i);
        createMarker(savedlatlng, name,MapLat,MapLon);
        bounds.extend(savedlatlng);
       }
        locationSelect.style.visibility = "visible";
        locationSelect.onchange = function() {
            var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
                google.maps.event.trigger(markers[markerNum], 'click');
        };
        });
    }
///Set up new marker
    function NewMarker(latLng,address) {
            markerNew = new google.maps.Marker({
                position: latLng,
                icon: imageNew,
                map: map,
                draggable: true,
                crossOnDrag:false
    });

  google.maps.event.addListener(markerNew, 'drag', function() {
     updateMarkerPosition(markerNew.getPosition());
     document.getElementById('locname').value = '';
  });

  google.maps.event.addListener(markerNew, 'dragend', function() {
     geocodePosition(markerNew.getPosition());
        var newlatLng = markerNew.getPosition(); // returns LatLng object
        map.setCenter(newlatLng);
     });
  }
  //Saved location marker
    function createMarker(savedlatlng, name,MapLat,MapLon) {
        var html = "<b>" + name + "</b>";
        var marker = new google.maps.Marker({
            map: map,
            icon: imageSave,
            position: savedlatlng,
            visible: false
      });

      google.maps.event.addListener(marker, 'click', function() {
            infowindow.close(); //Close MarkerNew infowindow
            markerNew.setVisible(false);//Close MarkerNew
            marker.setVisible(true);
            setAllMap(map); //Allows saved markers to be put back on map
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
            document.getElementById('latitude').value = MapLat;
            document.getElementById('longitude').value = MapLon;
            document.getElementById('locname').value = name;
      });
      markers.push(marker);
    }
    //Reads saved locations into dropdown menu
     function createOption(name, num) {
        var option = document.createElement("option");
            option.value = num;
            option.innerHTML = name;
            locationSelect.appendChild(option);
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request.responseText, request.status);
        }
    };
      request.open('GET', url, true);
      request.send(null);
    }

    function parseXml(str) {
      if (window.ActiveXObject) {
            var doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.loadXML(str);
            return doc;
            } else if (window.DOMParser) {
            return (new DOMParser).parseFromString(str, 'text/xml');
        }
    }

    function doNothing() {}

// Sets the map on all markers in the array.
    function setAllMap(map) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
    }
    }
// Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setAllMap(null);
        markerNew.setVisible(true);
    }
// Sets the map on all markers in the array.
    function setNewMap(map) {
        for (var i = 0; i < markerNew.length; i++) {
            markerNew[i].setMap(map);
    }
    }

// Removes the markers from the map, but keeps them in the array.
function clearMarkerNew() {
    google.maps.event.addListener(map, "click", function () {
        markerNew.setMap(null);
        alert("Marker has been removed from map, about to restore it");
            });
    }
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
 <body>
<body id = "main_body">
       </div>
   <div id="mainouter"> 
    <div class = "form description">
    <form action="reviewMember.php" method="post">

        <label style="font-size:1.4em;font-color:black;" class="description" for="location" >Where did you see it?* </label>
        <label class="description" for="location"></label>
            <div><select id="locationSelect" name="locationSelect" style="width:400px">
        <option value="loc_new" onclick="clearMarkers();">Select a new location</option>
        </select></div>

        <div id="map" style="height: 300px;width: 400px;margin-right: 0.9em;float:left;"></div>

    </form>
    </div>
    </body>
</html>

And php:

<?php  
require("connectMap.php"); 
// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node); 

// Opens a connection to a MySQL server
$con=mysqli_connect ($server, $user, $pass,$db);
if (!$con) {  die('Not connected : ' . mysqli_error($con));} 

session_start();

if(!isSet($_SESSION["email"],$_SESSION['uid'])) {
    // Redirect user to login page
    header("Location: login_final.php");
    exit();
}else {
    $userEmail = $_SESSION["email"];
 }

    // Select the member ID from the users table - to search for the id in the database
    $sql = "SELECT * FROM users WHERE email ='$userEmail' LIMIT 1";
    $user_query = mysqli_query($con, $sql);
    // Now make sure that user exists in the table
    $numrows = mysqli_num_rows($user_query);
    if($numrows < 1){
    echo "That user does not exist or is not yet activated, press back";
    exit(); 
    }

    // Fetch the user row from the query above
    while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
    $userID = $row["ID"];
    }

    // Select the member from the database table - this is to find the name of the user to input into the form and save into form database
    $query = "SELECT * FROM locations WHERE userID ='$userID' ";
    $result = mysqli_query($con,$query);
    $dayyear = "";

    if (!$result) {  
    die('Invalid query: ' . mysqli_error($con));
    } 

header("Content-type: text/xml"); 

// Iterate through the rows, adding XML nodes for each
while ($row = @mysqli_fetch_assoc($result)){  
  // ADD TO XML DOCUMENT NODE  
  $node = $dom->createElement("markerSave");  
  $newnode = $parnode->appendChild($node);   
  $newnode->setAttribute("loc_name",$row['locname']);
  $newnode->setAttribute("lat", $row['lat']);  
  $newnode->setAttribute("lng", $row['lng']);  
} 

echo $dom->saveXML();
?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
    • ¥15 Python中knn问题
    • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
    • ¥15 C# datagridview 单元格显示进度及值
    • ¥15 thinkphp6配合social login单点登录问题
    • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源