简体   繁体   English

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

[英]fetch values from database in php and store in array in js file

i am new to js and php. 我是js和php的新手。 i am using codeigniter hmvc. 我正在使用codeigniter hmvc。 i have a js file that displays markers in given radius on google maps, but the marker values(latitude & longitude) are provided in an array within the js file itself. 我有一个js文件,可在google地图上显示给定半径的标记,但标记值(纬度和经度)是在js文件本身的数组中提供的。 i need to fetch values from database and store in following format in js file. 我需要从数据库中获取值并以以下格式存储在js文件中。 i tried looking for answers, but unable to put it in the required format.i dont know how to use ajax and json either. 我试图寻找答案,但无法将其设置为必需的格式。我也不知道如何使用ajax和json。
also the geolocation part is not working, if anyone can tell me why and how- i would be grateful .thnks a lot in advance. 如果有人可以告诉我原因和方式,那么地理定位部分也无法正常工作-我将非常感激.thnks。 (if anyone marks it as duplicate .. plz provide link in comments.) here is my code: (如果有人将其标记为重复.. plz,请在评论中提供链接。)这是我的代码:

map2.js 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 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 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();

    }


}

If I understand you correctly, you wish to know how to fire an AJAX request to fetch data from server, and make it available in map2.js 如果我对您的理解正确,则希望了解如何触发AJAX请求以从服务器获取数据,并使其在map2.js中可用

Following it the syntax to make an AJAX call with jQuery: 遵循以下语法使用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
        }
    });

So now in your code, you will do something like this: 因此,现在在您的代码中,您将执行以下操作:

    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.
        }
    });

If I have misunderstood your question then comment on this answer. 如果我误解了您的问题,请对此答案发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数据库中获取数据到JavaScript文件并将其存储在数组中? - How to fetch data from the database into a javascript file and store it in array? 从HTML文件中获取选定的代码并存储在PHP数组中 - Fetch Selected code from a HTML file and store in an PHP array 如何从php文件中的数据库查询获取数组数据到ajax成功数据 - how to fetch the array data from database query in a php file to ajax sucess data 数据库中的数据 --&gt; 到 json 数组 in.php --&gt; 这个数组到 in.js 表中,然后通过调用 .js 文件在.html 中可视化 - Data from database --> to json array in .php --> this array into table in .js and then visualise it in .html by calling .js file 将值从文本文件存储到数组 - Store values to an array from a text file 将不同元素的 js 数组传递给 php 以进行验证并存储在 mysql 数据库中? - Passing a js array of different elements to php for validate and store in mysql database? 如何从对象数组中获取特定数据并存储在js(vue js)中的新数组中 - How to fetch particular data from array of objects and store in new array in js (vue js) 如何从 html 获取输入值数组到 JS - how to fetch array of input values from html to JS 从JSON编码jQuery获取PHP获取数组值 - Get php fetch array values from json encode jquery PHP / JS - 将值从 php 发送到 js 数组 - PHP / JS - Send values from php to a js array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM