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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站