我如何在谷歌地图中显示多个位置(Codeigniter)

时间:2018-01-25 07:36:05

标签: php codeigniter google-maps

我如何在Codeigniter中的谷歌地图中显示多个位置。我有一个阵列,包括纬度和经度。我想在地图中显示所有位置。

这是我从控制器传递到视图页面的$query数组,

Array ( 
        [0] => stdClass Object ([lat] => 37.45360256419911 [lng] => -122.16470718383789) 
        [1] => stdClass Object ([lat] => 37.45455646705577 [lng] => -122.1653938293457) 
        [2] => stdClass Object ([lat] => 37.451543303913226 [lng] => -122.16745376586914) 
      )   

我想在我的地图中显示所有这3个位置,现在它只标记1个位置。

<script>
    var map;
    var marker;
    var infowindow;
    var messagewindow;

    function initMap() {

    <?php
        foreach($query as $row){
            $lat=$row->lat;
            $lng=$row->lng;
    ?>

        var location = {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>};
        map = new google.maps.Map(document.getElementById('map'), {
            center: location,
            zoom: 13
        });

        var marker = new google.maps.Marker({
            position: location,
            map: map,
        });


        infowindow = new google.maps.InfoWindow({
            content: document.getElementById('form')
        });

        messagewindow = new google.maps.InfoWindow({
            content: document.getElementById('message')
        });

        google.maps.event.addListener(map, 'click', function(event) {
            marker = new google.maps.Marker({
            position: event.latLng,
            map: map
        });


        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
        });
    });

<?php
    }
?>
    }

3 个答案:

答案 0 :(得分:0)

未经测试,但您可以尝试这样做。将php代码放在前面并生成一个lat,lng坐标数组,转换为json以供initmap函数使用。遍历对象成员并添加新标记。

<?php
    $data=array();

    foreach($query as $row){
        $lat=$row->lat;
        $lng=$row->lng;
        $data[]=array('lat'=>$lat,'lng'=>$lng);
    }
    $json=json_encode( $data );
?>

<script>

    var map;
    var marker;
    var infowindow;
    var messagewindow;

    <?php
        echo "
        var json={$json};
        var lat={$lat}; 
        var lng={$lng};
        "
    ?>

    function initMap() {

        map = new google.maps.Map(document.getElementById('map'), {
            center: location,
            zoom: 13
        });

        infowindow = new google.maps.InfoWindow({
            content: document.getElementById('form')
        });

        messagewindow = new google.maps.InfoWindow({
            content: document.getElementById('message')
        });

        google.maps.event.addListener( map, 'click', function(event) {
            marker = new google.maps.Marker({
                position: event.latLng,
                map: map
            });
        });         


        for( var n in json ){
            var obj=json[ n ];
            lat=obj.lat;
            lng=obj.lng;
            var location = { lat:lat, lng:lng };

            var marker = new google.maps.Marker({
                position: location,
                map: map,
            }); 

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map, marker);
            });             
        }
    }
</script>

使用您在评论中提供的密钥,我收到有关无效密钥的错误,并且地图拒绝加载。然而,使用不同的密钥可以很好地进行一些改动。

我的数据库连接是mysqli,记录集的查询和处理可能与您选择的方法相同,也可能不同。您需要根据需要对其进行编辑,因为这些详细信息是从问题中省略的。

<?php
    /* emulated db connection */
    include __DIR__. '/db.php';

    /* get markers from a table */
    $sql='select `name`,`lat`,`lng` from markers limit 20';
    $result=$db->query( $sql );

?>
<!--

    Original question:
    https://stackoverflow.com/questions/48437784/how-i-show-multiple-location-in-google-map-codeigniter/48438084?noredirect=1#comment83871602_48438084

-->
<?php

    /* generate data array & convert to json */
    $data=array();
    /*
    foreach( $query as $row ){

    }
    */
    while( $row=$result->fetch_object() ){
        $lat=$row->lat;
        $lng=$row->lng;
        $name=$row->name;
        $data[]=array('name'=>$name,'lat'=>$lat,'lng'=>$lng);       
    }

    $json=json_encode( $data );
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Google maps - display markers</title>
        <script>

            var map;
            var marker;
            var infowindow;
            var messagewindow;



            <?php
                echo "
                var json={$json};
                var lat={$lat}; 
                var lng={$lng};
                "
            ?>

            function initMap() {
                var location=new google.maps.LatLng( lat,lng );
                map = new google.maps.Map( document.getElementById('map'), {
                    center: location,
                    zoom: 13
                });

                infowindow = new google.maps.InfoWindow({
                    content: document.getElementById('form')
                });

                messagewindow = new google.maps.InfoWindow({
                    content: document.getElementById('message')
                });

                google.maps.event.addListener( map, 'click', function(event) {
                    marker = new google.maps.Marker({
                        position: event.latLng,
                        map: map
                    });
                });         


                for( var n in json ){

                    var obj=json[ n ];
                    lat=obj.lat;
                    lng=obj.lng;
                    name=obj.name;

                    var location = new google.maps.LatLng( lat, lng );

                    var marker = new google.maps.Marker({
                        position: location,
                        title:name,
                        map: map,
                    }); 

                    google.maps.event.addListener( marker, 'click', function() {
                        var content=infowindow.getContent();                            
                        content.querySelector('input[name="lat"]').value=e.latLng.lat();                            
                        content.querySelector('input[name="lng"]').value=e.latLng.lng();                            
                        content.querySelector('input[name="name"]').value=this.title;

                        infowindow.open( map, this );
                    }.bind( marker )); /* bind to THIS marker */

                }
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=<API KEY>&callback=initMap'></script>
        <style>
            #map{
                width:800px;
                height:600px;
                float:none;
                margin:auto;
            }
        </style>
    </head>
    <body>
        <div id='map'></div>
        <form id='form'>
            <input type='text' name='lat' />
            <input type='text' name='lng' />
            <input type='submit' />
        </form>
        <div id='message'>unknown content</div>
    </body>
</html>

答案 1 :(得分:0)

It works fine for me...    
In controller : 

        function latLanLocation()
            {
               if($this->session->userdata('logged_in'))
               {
                    $session_data = $this->session->userdata('logged_in');
                    $data['title'] = 'Create client';

                    $ibo = $this->session->userdata['logged_in']['ibo'];

                    $latLanQuery = $this->db->query('select name,latitude,longitude from distributor_clients where sponsor='.$ibo.' AND status="A" AND latitude !=0 AND longitude !=0');

                    $userData = $latLanQuery->result_array();

                    $locations='[';
                    foreach ($userData as $key => $row) {
                        $name = $row['name'];
                        $longitude = $row['longitude'];                              
                        $latitude = $row['latitude'];

                        $locations .= '["'.$name.'","'.$latitude.'","'.$longitude.'"],';
                    }
                    $locations .= ']';

                    $data['markers'] =  $locations;

                    $this->load->view('location', $data);
               }
               else
               {
                 redirect('login', 'refresh');
               }
            }

    //In View folder create location.php
    // Html code for Google Map Javascript API
        <!DOCTYPE html>
        <html>
            <head>
                <style>
                    #mapCanvas {
                    height: 400px;
                    width: 100%;
                    }
                </style>
            </head>
            <body>
                <div id="mapCanvas"></div>
                <script>
                    function initMap() {
                        var map;
                        var bounds = new google.maps.LatLngBounds();
                        var mapOptions = {
                            mapTypeId: 'roadmap'
                        };

                        map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
                        map.setTilt(50);

                        var markers = <?php echo $markers; ?>

                        // Add multiple markers to map
                        var infoWindow = new google.maps.InfoWindow(), marker, i;

                        // Place each marker on the map  
                        for( i = 0; i < markers.length; i++ ) {
                            var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
                            bounds.extend(position);
                            marker = new google.maps.Marker({
                                position: position,
                                map: map,
                                title: markers[i][0]
                            });                                           


                            // Center the map to fit all markers on the screen
                            map.fitBounds(bounds);
                        }

                        // Set zoom level
                        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                            this.setZoom(14);
                            google.maps.event.removeListener(boundsListener);
                        });

                    }
                    // Load initialize function
                    google.maps.event.addDomListener(window, 'load', initMap);
                </script>
                <script async defer
                    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap"></script>
            </body>
        </html>

最终输出: enter image description here

答案 2 :(得分:-1)

此代码可以显示多个不同的标记。希望这能帮助你。

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Markers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>

        /* Always set the map height explicitly to define the size of the div
        * element that contains the map. */
        #map {
            height: 100%;
        }

        /* Optional: Makes the sample page fill the window. */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
        var map;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {             
                zoom: 16,
                center: new google.maps.LatLng(-33.91722, 151.23064),
                mapTypeId: 'roadmap'
            });

            var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
            var icons = {
                library: {
                    icon: iconBase + 'library_maps.png'
                },
                info: {
                    icon: iconBase + 'info-i_maps.png'
                }
            };

            var features = [

                // do looping here and replace LatLng value using foreach PHP.

                {
                    position: new google.maps.LatLng(-33.91721, 151.22630),
                    type: 'info'
                }, {
                    position: new google.maps.LatLng(-33.91539, 151.22820),
                    type: 'library'
                }, 

            ];

            // Create markers.
            features.forEach(function(feature) {
                var marker = new google.maps.Marker({
                    position: feature.position,
                    icon: icons[feature.type].icon,
                    map: map
                });
            });
        }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

来源:https://developers.google.com/maps/documentation/javascript/custom-markers