douzhongpi9734 2015-12-13 15:50
浏览 137
已采纳

php和谷歌地图api

New to coding but had an idea to make my life easier at work - maybe I am being too ambitious!!!

I found some code that allows to to show push pins on a google map that are placed within the code via a variable - postcode- I need to pass postcodes from an excel csv file into the code and then display this on the map.

the original code is NOT mine but I am pasting here to show the basis on my query. This is not PHP but felt I wanted to use PHP to link to excel - if this is wrong please feel free to point me in the right direction!!!

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    var geocoder;
    var map;
    var markers = [];
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(40.768505,-111.853244);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            addPostCode ('BA2 3RA');
        addPostCode ('BN1 1AB');
        addPostCode ('BA3 3JG');
           }

    function addPostCode(zip) {
        geocoder.geocode( { 'address': zip}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK)
        {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            name: zip
        });
        markers.push(marker);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        });
    }

    function checkZip(zip)
    {
        var distance = Number.MAX_VALUE;
        var index = 0;
        geocoder.geocode( { 'address': zip}, function(results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                for(ix=0; ix< markers.length; ix++)
                {
                    var tmp = getDistance(results[0].geometry.location, markers[ix].position);
                    if (tmp < distance)
                    {
                        distance = tmp;
                        index = ix;
                    }
                }
                alert('nearest zipcode is :' + markers[index].name);
            }
        });
    }

    function getDistance(latlng1, latlng2)
    {
        var R = 6371; // Radius of the earth in km
        var dLat = (latlng2.lat()-latlng1.lat()) * Math.PI / 180;  // Javascript functions in radians
        var dLon = (latlng2.lng()-latlng1.lng()) * Math.PI / 180;
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlng1.lat()  * Math.PI / 180) * Math.cos(latlng2.lat()  * Math.PI / 180) *
            Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c; // Distance in km
        d = d * 0.621371192; // convert to miles
        return d;
    }
</script>
</head>
<body onload="initialize()">
  <div>
    <input id="address" type="textbox" value="">
    <input type="button" value="Geocode" onclick="checkZip(getElementById('address').value)">
  </div>
<div id="map_canvas" style="height:90%"></div>
</body>
</html>
  • 写回答

2条回答 默认 最新

  • duanliao3826 2015-12-14 00:41
    关注

    I see you've got as far as getting the CSV data into a PHP array. So the next step is to pass that to a JavaScript array. To do this we rely on the fact that, in any .php file that contains a mixture of HTML markup and PHP code (the HTML of course being outside <?php .... ?> tags and the PHP inside them), at runtime the PHP interpreter goes through the file FIRST and processes the PHP. So if you have an echo statement in the PHP, it will echo whatever's being echoed into the HTML, which is then parsed as HTML markup with whatever values were written into it. Note how we can even have a PHP loop going on around HTML (or in this case Javacript embedded in the HTML), all because the PHP gets processed before anything else!

    So in a .php script do:

    <!DOCTYPE html>
    <?php
    
    include "getCsvData.php";   // this is where you put the data into a PHP array called $dataArray;
    // now we exit the PHP and do the HTML including our Javascript...
    
    ?>
    [HTML head code here]
    <body>
    [more HTML markup here, we usually put javascripts at the end]
    
    <script>
    var markers = [];   // your javascript array
    
    <?php 
    // start a loop in the PHP
    for( $i=0; $i < 10; $i++)
    {
    // then back to the javascript...
    ?>
    arr[<?php echo $i;?>] = <?php echo $dataArray[$i]; ?>;  // note the final semi-colon ; here
    
    <?php } ?>
    </script>
    

    So that's it (hope I haven't got any typos there, apologies if I have, you'll need to test it out). Once you have it working if you display the web page in your browser and right click on it and choose the browser's "Source code" option, you will see the <script> tags have magically gained 10 lines of javascript code adding the array values. (I used 10 for convenience in this example, you'll need to find out how big your PHP data array is using count()).

    Don't forget that last little line of php to close the php loop - it's just a single close curly bracket inside PHP tags. Note also the doctype line needs to be the first line in the file.

    Finally, since you're new to Google Maps and just found that bit of code to work from, be sure to go to the Google API documentation at https://developers.google.com/maps/documentation/javascript/tutorial - it's very clear. Yes, as you say, you're certainly ambitious, but that's good and it will all be an excellant introduction into PHP coding and Google Maps as well. All the best with it!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含