javascript - 在php中从数据库中获取值并将其存储在js文件中的数组中

标签 javascript php codeigniter google-maps

我是 js 和 php 新手。我正在使用 codeigniter hmvc。 我有一个 js 文件,它在谷歌地图上显示给定半径的标记,但标记值(纬度和经度)在 js 文件本身的数组中提供。我需要从数据库中获取值并以以下格式存储在js文件中。我尝试寻找答案,但无法将其放入所需的格式。我也不知道如何使用 ajax 和 json。
另外,地理定位部分不起作用,如果有人能告诉我原因和方法-我将不胜感激。提前多谢。 (如果有人将其标记为重复..请在评论中提供链接。) 这是我的代码:

map2.js

var map = null;
  var radius_circle;
  var markers_on_map = [];
  var geocoder;
  var infowindow;

  //all_locations is just a sample, i need to load these from database in same format
  var all_locations = [
      {type: "RTO River(eventname)", name: "river 1(eventaddress)", lat: 18.53109147547569, lng: 73.8605202502929},
      {type: "KP chowk", name: "square 1", lat: 18.541304420729684, lng: 73.88412368962395},
      {type: "Westline chowk", name: "square 2", lat: 18.539208985720602, lng: 73.90377891728508},
      {type: "Mawpatta inner circle ", name: "circle 1", lat: 18.51581160734747, lng: 73.92665279576408},
      {type: "Phoenix road", name: "road 1", lat: 18.560731744351386, lng: 73.91761911580193}
  ];

  //initialize map on document ready
  $(document).ready(function(){
      var latlng = new google.maps.LatLng(18.52043, 73.85679); 
      var myOptions = {
        zoom: 1,
        center: latlng,
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      geocoder = new google.maps.Geocoder();
      google.maps.event.addListener(map, 'click', function(){
           if(infowindow){
             infowindow.setMap(null);
             infowindow = null;
           }
      });
  });



function showCloseLocations() {
    var i;
    var radius_km = $('#radius_km').val();
    var address = $('#address').val();


    //remove all radii and markers from map before displaying new ones
    if (radius_circle) {
        radius_circle.setMap(null);
        radius_circle = null;
    }
    for (i = 0; i < markers_on_map.length; i++) {
        if (markers_on_map[i]) {
            markers_on_map[i].setMap(null);
            markers_on_map[i] = null;
        }
    }
      //---------

      //----------

    if (geocoder) {
        geocoder.geocode({'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    var address_lat_lng = results[0].geometry.location;
                    radius_circle = new google.maps.Circle({
                        center: address_lat_lng,
                        radius: radius_km * 1000,
                        clickable: false,
                        map: map
                    });
                    if (radius_circle) map.fitBounds(radius_circle.getBounds());
                    for (var j = 0; j < all_locations.length; j++) {
                        (function (location) {
                            var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng);
                            var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker
                            if (distance_from_location <= radius_km * 1000) {
                                var new_marker = new google.maps.Marker({
                                    position: marker_lat_lng,
                                    map: map,
                                    title: location.name
                                });                                     
                                google.maps.event.addListener(new_marker, 'click', function () {
                                    if(infowindow){
             infowindow.setMap(null);
             infowindow = null;
           }
                                    infowindow = new google.maps.InfoWindow(
            { content: '<div style="color:red">'+location.name +'</div>' + " is " + distance_from_location + " meters from my location",
              size: new google.maps.Size(150,50),
              pixelOffset: new google.maps.Size(0, -30)
            , position: marker_lat_lng, map: map});
                                });
                                markers_on_map.push(new_marker);
                            }
                        })(all_locations[j]);
                    }
                } else {
                    alert("No results found while geocoding!");
                }
            } else {
                alert("Geocode was not successful: " + status);
            }
        });
    }
  }

mymapview11.php

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY">
</script>
<script type="text/javascript" 
        src="<?php echo base_url().'js/map2.js'; ?>">
</script>

<script>
    // get current location with HTML5 geolocation API.
    //not working
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                lat.value  =  position.coords.latitude ;
                lng.value  =  position.coords.longitude;
                info.nodeValue =  position.coords.longitude;
                // set the current position to the map and create info window with (Here Is Your Location) sentense
                infoWindow.setPosition(pos);
                infoWindow.setContent('Here Is Your Location.');
                // set this info window in the center of the map
                map.setCenter(pos);
                // draw circle on the map with parameters
                DrowCircle(mapOptions, map, pos, km);

            }, function() {
                // if user block the geolocation API and denied detect his location
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());

        }
</script>
<script>

$.get("<?php echo base_url().'mapme/map11b.php'; ?>", function(data) {
  alert("Data Loaded: " + data);
});
</script>
<script>
    // get current location with HTML5 geolocation API.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                lat.value  =  position.coords.latitude ;
                lng.value  =  position.coords.longitude;
                info.nodeValue =  position.coords.longitude;
                // set the current position to the map and create info window with (Here Is Your Location) sentense
                infoWindow.setPosition(pos);
                infoWindow.setContent('Here Is Your Location.');
                // set this info window in the center of the map
                map.setCenter(pos);
                // draw circle on the map with parameters
                //DrowCircle(mapOptions, map, pos, km);

            }, function() {
                // if user block the geolocation API and denied detect his location
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());

        }
</script>
</head>

<body style="margin:0px; padding:0px;">
 <input id="address" value="Pune" placeholder="Input Address"/>
 <select id="radius_km">
     <option value=1>1km</option>
     <option value=2>2km</option>
     <option value=5>5km</option>
     <option value=10>10km</option>
     <option value=15>15km</option>
     <option value=20>20km</option>
     <option value=30>30km</option>
     <option value=50>50km</option>
 </select>
 <button onClick="showCloseLocations()" id="showlocationbtn">Show Locations In Radius</button>

    <script>

</script>
 <div id="map_canvas"  style="width:500px; height:300px;"></div>
</body>
</html>

mdl_map.php

 <?php

if (!defined(BASEPATH))
    exit(No direct script access allowed);


class Mdl_map extends CI_Model
{


    function getlocation()
    {
        $this->db->select('*');
            $this->db->from('eventstable');
            $this->db->order_by('eventstart','ASC');
            $this->db->where('eventpermission =',1);
            $this->db->where('eventstatus =',1);

            $query = $this->db->get();

        return $query->result();

    }


}

最佳答案

如果我理解正确的话,您希望知道如何触发 AJAX 请求以从服务器获取数据,并使其在 map2.js 中可用

遵循使用 jQuery 进行 AJAX 调用的语法:

    $.ajax({
        url: 'http://yourdomain/controller/method/getparamsifany',
        type: 'POST',  // POST/GET Request Method
        data: {key: value, key2: value2},      // An object with data that you want to pass
        success: function (response) {
            // Response callback
            // Code to be executed after receiving the response from AJAX
        }
    });

所以现在在您的代码中,您将执行以下操作:

    var map = null;
    var radius_circle;
    var markers_on_map = [];
    var all_locations = [];
    var geocoder;
    var infowindow;

    $.ajax({
        url: 'request url to a method to fetch required data',  // Make sure you return the result after json_encode($your_db_result)
        type: 'GET',
        data: paramsObj,
        success: function (response) {
            // I am assuming your required data is in response as data
            all_locations = response.data;
            // Initialize and render your map after this otherwise you might have to render the map again because of the changes in all_locations array.
        }
    });

如果我误解了您的问题,请对此答案发表评论。

关于javascript - 在php中从数据库中获取值并将其存储在js文件中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44795079/

相关文章:

javascript - 如何禁用 ExtJS 中网格上的复选框?

javascript - 如何在单击时切换 Slick slider (向下滑动并向上滑动)

javascript - axios 在服务器之间传输数据

php - Codeigniter:如何在迭代第一个表值时从第二个表获取计数

php - 插入后无法获取行值

javascript - 为什么我网站上的所有文字都是大写

PHP 替换数组值

php - 设置服务器端脚本以连续记录来自数据库中 API 的流式 JSON 数据?

php - mysql (php) 上的时间戳问题

php - ExtJS 网格存储 - 通过 CodeIgniter 将信息写入 "Save"/"Update"上的 MySQL