javascript - (PHP/JS)Google Maps API 3在IE,FF和iPad(Safari/Chrome)中未获得结果,但在Chrome&M8 Android( native /Chrome)中获得结果

标签 javascript php google-maps-api-3 google-places-api google-geocoding-api

问题说明

对于我来说,这不是一件容易的事情,因为我不确定到底发生了什么。基本上,我目前正在使用以下Google API:




地理编码API







Google Maps JavaScript API v3







Places API






我一直在Windows 7上使用Google Chrome浏览器,并且已经成功创建了一个使用Google Maps API V3的系统,并允许我根据给定的时间创建的地理编码的LatLng搜索位置并拉回该位置附近的商家位置是通过Google Geocoder发送的。

我的Google Chrome浏览器在PC上运行良好,但在FireFox或Internet Explorer中无法运行。除此之外,它也不能在装有Safari或Chrome的iPad上运行,但是在本地浏览器和Chrome上的HTC M8上都可以运行。

基本上,用户搜索一个位置(仅在第二个输入框中搜索“ Southport”,此刻在第一个输入中没有任何内容),并获得25公里以内的商家列表。此搜索功能可在Chrome中按预期返回结果,但不会返回结果,也不会将地图居中显示在正确的位置。

在搜索过程中生成了一个业务xml模式。在FireFox中通过Firebug进行检查时为空。

谷歌驱动器下载时,在底部提供了有关系统在工作时的外观和不工作时的外观的信息,您将需要HTTPS:


地图的生成方式


最初,load()在加载时运行:




<body class="search" onload="load();">






这会激发initialize();

运行的代码是:




function initialize() {
    var input = document.getElementById('loc');
    var options = {componentRestrictions: {}};
                 
    new google.maps.places.Autocomplete(input, options);
}
             
google.maps.event.addDomListener(window, 'load', initialize);





仅供参考:在此之后,调用了许多脚本,我相信这些脚本已包含在Google API中,因为它们不是经过硬编码的(顺序为:common.js,util.js,geocoder.js,controls.js,places_impl.js ,map.js,infowindow.js,onion.js,stats.js和marker.js)。

在调用上述脚本之前,我已经引用了Google Maps API。这再次为未硬编码的其他.js文件添加了更多引用:




<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=EXAMPLE_APIKEY&amp;sensor=false&amp;libraries=places"></script>
<script src="https://maps.gstatic.com/maps-api-v3/api/js/20/5/main.js"></script>
<script src="https://maps.gstatic.com/maps-api-v3/api/js/20/5/places.js"></script>  
<script type="text/javascript" src="/library/inc/structure/business/widgets/google-map/google-map.js"></script>






您可能会注意到,在调用Google Map API之后,还会调用main.js和places.js,它们不会经过硬编码,在调用此google-map.js之后,然后在所有这些下面进行initialize()函数与其他提到的脚本一起被调用。

加载();导致调用以下函数(顶部的var是所有google-map.js的公共var):




//<![CDATA[
    var map;
    var businesses = [];
    var infoWindow;
    var locationSelect;

    function load() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(40, -100),
        zoom: 4,
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
      });
      infoWindow = new google.maps.InfoWindow();

      locationSelect = document.getElementById("locationSelect");
      locationSelect.onchange = function() {
        var businessNum = locationSelect.options[locationSelect.selectedIndex].value;
        if (businessNum != "none"){
          google.maps.event.trigger(businesses[businessNum], 'click');
        }
      };
   }






这将创建地图,并在用户在搜索结果中选择位置时进行侦听。

得到结果

当search.php加载时,将运行以下功能:




var $_POST = <?php echo json_encode($_POST); ?>;    

        function searchLocation() {
         var address = $_POST["loc"];
         var geocoder = new google.maps.Geocoder();
         geocoder.geocode({address: address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
            searchLocationsNear(results[0].geometry.location);
           } else {
             alert(address + ' not found');
           }
         });
       }
        window.onload = searchLocation;







依次运行searchLocationNear(); :




function searchLocationsNear(center) {
     clearLocations();

     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = '/library/inc/structure/business/widgets/google-map/google-map.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     downloadUrl(searchUrl, function(data) {
       var xml = parseXml(data);
       var businessNodes = xml.documentElement.getElementsByTagName("business");
       var bounds = new google.maps.LatLngBounds();
       for (var i = 0; i < businessNodes.length; i++) {
        var business_id = businessNodes[i].getAttribute("business_id");
         var name = businessNodes[i].getAttribute("name");
         var address = businessNodes[i].getAttribute("address");
         createSearchResults(name, distance, i, business_id, address);
         createMarker(latlng, name, address);
         bounds.extend(latlng);
       }
       map.fitBounds(bounds);
       locationSelect.style.visibility = "visible";
       locationSelect.onchange = function() {
         var businessNum = locationSelect.options[locationSelect.selectedIndex].value;
         google.maps.event.trigger(businesses[businessNum], 'click');
       };
      });
    }







此LatLng通过网址推送到Google-Map.php:




/library/inc/structure/business/widgets/google-map/google-map.php?lat=' +     center.lat() + '&lng=' + center.lng() + '&radius=' + radius;






在google-map.php中,发生以下情况:




$database="db_name";
$username="db_user";
$password="db_password";

$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];

// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("businesses");
$parnode = $dom->appendChild($node);

// Opens a connection to a mySQL server
$connection=mysql_connect ($database, $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}

// Search the rows in the markers table
$get_business_query = sprintf("SELECT business_id, address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM businesses HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",  mysql_real_escape_string($center_lat),  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));
$get_business_result = mysql_query($get_business_query);

if (!$get_business_result) {
  die("Invalid query: " . mysql_error());
}

header("Content-type: text/xml");
  
while ($get_business_row = @mysql_fetch_assoc($get_business_result))
{
  $businessID         = $get_business_row['business_id'];
 
  $node = $dom->createElement("business");
 
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("business_id", $get_business_row['business_id']);
  $newnode->setAttribute("name", $get_business_row['name']);
  $newnode->setAttribute("address", $get_business_row['address']);
}
echo $dom->saveXML();






然后,一个聪明的MySQL查询可以算出哪些企业位于25公里半径范围内(目前已进行了硬编码,但最终会成为一种选择)。




$get_business_query = sprintf("SELECT business_id, address, name, lat, lng,  ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM businesses HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",  mysql_real_escape_string($center_lat),  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));
$get_business_result = mysql_query($get_business_query);






然后遍历结果的行,并为每个行创建一个XML节点:





while ($get_business_row = @mysql_fetch_assoc($get_business_result))
{
  $businessID         = $get_business_row['business_id'];
 
  $node = $dom->createElement("business");
 
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("business_id", $get_business_row['business_id']);
  $newnode->setAttribute("name", $get_business_row['name']);
  $newnode->setAttribute("address", $get_business_row['address']);
}
echo $dom->saveXML();






然后,Google-Map.js在searchLocationNear()中读取生成的XML输出。

其余的Google-Map.js如下:




function createMarker(latlng, name, address) {
      var html = "<b>" + name + "</b> <br/>" + address;
      var marker = new google.maps.Marker({
        map: map,
        position: latlng
      });
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
      businesses.push(marker);
    }

    function createSearchResults(name, distance, num, business_id, address) {
      var li = document.createElement("li");
      li.value = num;
      li.setAttribute("onmouseover", "selectBusinessOnMap(" + num + ")");
      li.setAttribute("onmouseout", "deselectBusinessOnMap(" + num + ")");
      //Start Search Results ---------------------------------

      //Name
      li.innerHTML += "<div class=\"result-name\"><a href=\"/business/" + business_username + "\" \">" + (num + 1) + ". " + name + "</a></div>";

      //Distance
      li.innerHTML += "<div class=\"result-distance\">(" + distance.toFixed(1) + ")";
      

      //End Search Results ---------------------------------
      locationSelect.appendChild(li);
    }

    function selectBusinessOnMap(num) {
      
        var businessNum = num;
        google.maps.event.trigger(businesses[businessNum], 'click');

    }

    function deselectBusinessOnMap(num) {
      
        infoWindow.close();
    }

    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() {}

    //]]>







链接到网站



MyWorthy.Services

忽略第一个输入框,然后在第二个中输入Southport并进行搜索。

根据问题的介绍,它仅对我适用于Chrome,不适用于IE或Firefox等。




验证错误


几个验证错误引起了我的注意,但是我不确定是否是原因,也不会通过w3c将任何值提交到搜索中,因此不确定是否是某些错误的原因


[在将本文档检查为HTML 4.01 Transitional时发现错误!] [11]



与我进行的研究的链接

链接到其他具有类似问题的问题,由于我对问题的实际出处缺乏了解,因此我尝试运用于我自己的情况时没有太多运气:


Google maps api 3 with places DEMO works only in Chrome… why?-这似乎是我最好的描述...



  在Firefox和IE9中也是如此……映射和元素都很好,但是当您按下搜索时,所有复选框都会重置,搜索框不会产生任何结果-有效地重置。


...在评论中被提及,我感到这是我的问题正在发生的事情,尽管我不确定。


2. [Google Maps V3 JavaScript只能在Chrome中使用吗?]


3. [PHP代码可在Chrome上运行,但不能在Firefox或IE上运行]


4. [Google Maps API GeoJSON不适用于IE 11,但可在Chrome中使用]-此链接向我介绍了此链接...


  <meta http-equiv="X-UA-Compatible" content="IE=edge" />


...不确定这是否会产生影响,以后我一回到家就会尝试它,并使用我的发现更新这个问题(编辑:看来这已经在我的代码中了)。


5. [如果不存在,有什么区别?]


6. [Google Maps v2到v3 API包装器可在Chrome中使用,但不能在Firefox / IE中使用]


7. [Google Maps V3 JavaScript仅在Chrome中有效吗?]


8. [Google Maps API和Javascript问题。它可以在Firefox中完美运行,为什么不使用Internet Explorer?]-我最初会以为略有关联,因为错误仅与IE有关,但是我注意到了这一点...


  好吧,我知道了。原来我有一个变量名冲突。
   我通过将map div DOM元素从map重命名为其他东西来修复它。
  它现在可以在Firefox和IE中很好地工作。
  感谢您在这里得到的所有帮助。


……这使我认为也许我也将map div DOM元素命名为“ map”。编辑:尝试过此操作,更改了几位称为“地图”的内容,但未更改任何内容,但不确定是否是DOM元素。


9. [Google Maps api不在Firefox和IE中显示,但在Chrome和safari中显示] [9]-我在旅途中也多次看到此错误,但是我不认为这是正在发生的我可能是错的。基本上在FF和IE中,一些用户会看到一个灰色框,该图应归因于CSS错误。我实际上看到的是以美国为中心的地图。



所以...请帮助... !!!

关于问题,布局,研究等的任何反馈将不胜感激,因此我将学习如何真正为StackOverflow做出贡献。

同样,所有帮助和建议都将不胜感激,因为我不知道从哪里开始这个问题,因为我真的不习惯仅在Chrome中运行!通常只用于IE无法正常工作!!!



------------请查看指向仅允许2个网址而无法添加的问题的链接-----------

2:http://gotoanswer.com/?q=Google+Maps+V3+JavaScript+works+only+in+Chrome%3F


3:http://stackoverflow.com/questions/19693799/php-code-works-on-chrome-but-not-on-firefox-or-ie


4:http://stackoverflow.com/questions/26678721/google-maps-api-geojson-not-working-with-ie-11-but-works-in-chrome


5:http://stackoverflow.com/questions/6771258/whats-the-difference-if-meta-http-equiv-x-ua-compatible-content-ie-edge-e


6:http://stackoverflow.com/questions/20099944/google-maps-v2-to-v3-api-wrapper-working-in-chrome-but-not-in-firefox-ie


7:http://stackoverflow.com/questions/9760727/google-maps-v3-javascript-works-only-in-chrome


8:http://software.programming4.us/forums/t/101675.aspx


9:http://groups.google.com/forum/#!topic/google-maps-api/50z4juKrYEM


11:http://validator.w3.org/check?uri=http%3A%2F%2Fmyworthy.services%2Fsearch.php&charset=%28detect+automatically%29&doctype=Inline&ss=1&outline=1&group=1&No200=1&st=1&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices


编辑


这是在搜索“ Southport”并获得结果时的外观:

http://drive.google.com/file/d/0B7Rzr6uvzmvAUVBfeWUzNU5FX0k/view?usp=sharing

当它在FF和IE中均不起作用时,它应该是这样的:

http://drive.google.com/file/d/0B7Rzr6uvzmvAdzlGTGhiQldpZmM/view?usp=sharing

最佳答案

您的问题是在“ search.php”中使用的window.onload。对于我来说,它不会在IE10或Firefox中启动,但会在Chrome上启动。
我没有找到内容和位置,但是我很确定在您的代码或包含的某些库中的其他地方使用window.onload还有其他内容。
那是行不通的,只有分配给window.onload的最后一个回调才会实际触发。阅读此内容:Best practice for using window.onload

关于javascript - (PHP/JS)Google Maps API 3在IE,FF和iPad(Safari/Chrome)中未获得结果,但在Chrome&M8 Android( native /Chrome)中获得结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29355291/

相关文章:

javascript - 使用javascript计算对应字段

javascript - 根据值设置表单名称

asp.net - Google Maps API 3 如何调用初始化而不将其放入正文 onload

php - MySQL > 总结为单个查询(包括谷歌地图)

javascript - 更改检测在 Firefox 中无法正常运行

javascript - HTML 按钮仅适用于网页重新/加载

javascript - 使用 Typescript 将 Thunk 发送到商店

php - 访问 Web 服务器文档根文件夹上方的文件

php - 使用 Drupal 可编辑时间表

google-maps - Google map 上的平移点到屏幕上的特定像素位置(API v3)