【问题标题】:Angularjs get json not working in google mapAngularjs让json在谷歌地图中不起作用
【发布时间】:2017-05-30 07:26:34
【问题描述】:

我想在地图上向您显示该地区的地点列表。使用下面的代码我可以展示这一点,但我不知道如何从 MySQL 中提取数据。如何使用 ajax.php 更改 $ scope.names 下面的部分。

这段 html 代码运行良好:

var hotelApp = angular.module('hotelApp', [])
        hotelApp.controller('ContentControler', function ($scope, $http) {
    	var imageUrl = base_url + 'marker.png';
        var mapOptions = {
            zoom: 4,
            center: new google.maps.LatLng(40.0000, -98.0000),

        mapTypeId: google.maps.MapTypeId.TERRAIN
        }
        $scope.location_name = "";
    	
    $http.get('properties.php').success(function(data) {
            $scope.namesx = data;
        });
     	
        $scope.names = [{
            prop_Name: name,
            prop_Addr: '123 Easy Street',
            prop_Price: 325.00,
            prop_Dist: .25,
            prop_Desc: 'This is the First Location.',
            lat: 43.7000,
            long: -79.4000
        }, {
            prop_Name: 'Location 2',
            prop_Addr: '456 Easy Street',
            prop_Price: 114.00,
            prop_Dist: 3,
            prop_Desc: 'This is the Second Location.',
            lat: 40.6700,
            long: -73.9400
        }, {
            prop_Name: 'Location 3',
            prop_Addr: '789 Easy Street',
            prop_Price: 98.00,
            prop_Dist: 4,
            prop_Desc: 'This is the Third Location.',
            lat: 41.8819,
            long: -87.6278
        }, {
            prop_Name: 'Location 4',
            prop_Addr: '1011 Easy Street',
            prop_Price: 150.00,
            prop_Dist: 1,
            prop_Desc: 'This is the Fourth Location.',
            lat: 34.0500,
            long: -118.2500
        }, {
            prop_Name: 'Location 5',
            prop_Addr: '1213 Easy Street',
            prop_Price: 250.00,
            prop_Dist: 7,
            prop_Desc: 'This is the Firth Location.',
            lat: 36.0800,
            long: -115.1522
        }];
        $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

        $scope.markers = [];

        var infoWindow = new google.maps.InfoWindow({maxWidth: 350});

        var createMarker = function (info) {

            var marker = new google.maps.Marker({
                map: $scope.map,
                position: new google.maps.LatLng(info.lat, info.long),
                title: info.prop_Name,
    			deniz: info.prop_Addr,
    			animation: google.maps.Animation.DROP,
    			
            });
    		
            marker.content = '<div id="iw-container"><div class="iw-content"><div class="iw-subTitle">' + '<li>' + info.prop_Desc + '</li>' + '<li>' + info.prop_Addr + '</li>' + '<li>' + info.prop_Price + '</li>' + '<li>' + info.prop_Dist + '</li>' + '</div></div></div>';

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.setContent('<div class="iw-subTitle">' + marker.title + '</div>' + marker.content);
                infoWindow.open($scope.map, marker);
            });
    		
    		google.maps.event.addListener($scope.map, 'click', function() {
    			infoWindow.close($scope.map, marker);
    		});
    		
            $scope.markers.push(marker);
    		
    		google.maps.event.addListener(infoWindow, 'domready', function() {

    		// Reference to the DIV that wraps the bottom of infowindow
    		var iwOuter = $('.gm-style-iw');

    		/* Since this div is in a position prior to .gm-div style-iw.
    		 * We use jQuery and create a iwBackground variable,
    		 * and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
    		*/
    		var iwBackground = iwOuter.prev();

    		// Removes background shadow DIV
    		iwBackground.children(':nth-child(2)').css({'display' : 'none'});

    		// Removes white background DIV
    		iwBackground.children(':nth-child(4)').css({'display' : 'none'});

    		// Moves the infowindow 115px to the right.
    		iwOuter.parent().parent().css({left: '115px'});

    		// Moves the shadow of the arrow 76px to the left margin.
    		iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    		// Moves the arrow 76px to the left margin.
    		iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});

    		// Changes the desired tail shadow color.
    		iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'silver 0px 1px 6px', 'z-index' : '1'});

    		// Reference to the div that groups the close button elements.
    		var iwCloseBtn = iwOuter.next();

    		// Apply the desired effect to the close button
    		iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9'});

    		// If the content of infowindow not exceed the set maximum height, then the gradient is removed.
    		if($('.iw-content').height() < 140){
    		  $('.iw-bottom-gradient').css({display: 'none'});
    		}

    		// The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
    		iwCloseBtn.mouseout(function(){
    		  $(this).css({opacity: '1'});
    		});
    		});

        }

        for (i = 0; i < $scope.names.length; i++) {
            createMarker($scope.names[i]);
        }

        $scope.openInfoWindow = function (e, selectedMarker) {
            e.preventDefault();
            google.maps.event.trigger(selectedMarker, 'click');
        }
    	
    	
    	
    	
    	$scope.goster = function (e, selectedMarker) {
            e.preventDefault();
    		selectedMarker.setIcon(imageUrl);
    		selectedMarker.setAnimation(google.maps.Animation.BOUNCE);
        }
    	
    	$scope.gizle = function (e, selectedMarker) {
            e.preventDefault();
    		selectedMarker.setIcon(null);
            selectedMarker.setAnimation(null);
        }
    	
        //Max Location Price
        $scope.maxPrice = 500;
        $scope.priceRangeFilter = function (location) {
            return location.prop_Price <= $scope.maxPrice;
        };
        //Max POI Radius
        $scope.maxRadius = 15;
        $scope.radiusRangeFilter = function (location) {
            return location.prop_Dist <= $scope.maxRadius;
        };

        $scope.$watch('nas',

        function (newValue, oldValue) {
            for (jdx in $scope.markers) {
                $scope.markers[jdx].setMap(null);
            }
            $scope.markers = [];
            for (idx in $scope.nas) {
                createMarker($scope.nas[idx]);
            }
        }, true);

    });
#map {
    height:400px;
    width:100%;
}
.gm-style-iw {
	width: 350px !important;
	top: 15px !important;
	left: 0px !important;
	background-color: #fff;

	border: 1px solid silver;
	border-radius: 0px;
	
	-webkit-box-shadow: 48px 9px 14px -10px rgba(0,0,0,0.2);
	-moz-box-shadow: 48px 9px 14px -10px rgba(0,0,0,0.2);
	box-shadow: 48px 9px 14px -10px rgba(0,0,0,0.2);

}
#iw-container {
	margin-bottom: 0px;
}
#iw-container .iw-title {
	font-family: 'Open Sans Condensed', sans-serif;
	font-size: 22px;
	font-weight: 400;
	padding: 10px;
	background-color: #48b5e9;
	color: white;
	margin: 0;
	border-radius: 0;
}
#iw-container .iw-title a{
	color: white;
	text-decoration: none;
}
#iw-container .iw-content {
	width:330px;
	font-size: 13px;
	line-height: 18px;
	font-weight: 400;
	margin-right: 1px;
	color:#aaa;
	padding: 10px;
	max-height: 400px;
	overflow-y: hidden;
	overflow-x: hidden;
}
.iw-content a{
	color:#777;
	text-decoration: none;
}
.iw-content img {
	margin: 0;	
}
.iw-subTitle {
	font-size: 16px;
	font-weight: 700;
	padding: 5px 0;
}
.iw-bottom-gradient {
	position: absolute;
	width: 326px;
	height: 25px;
	bottom: 10px;
	right: 18px;
	background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
	background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
	background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
	background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
}
<html lang="tr">
    <head>
    <meta charset="utf-8">
    <title>Airbnb Çalışmam</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?key=AIzaSyBVgASeglOFj8kUSEnVQVfr4vuaD1pVxI8&sensor=false&libraries=places" charset="UTF-8"></script>
    <script type="text/javascript" charset="UTF-8">
    	var base_url = "http://www.odevi.org/test/airbnb/airbnb_map/";
    </script>
    </head>
    <body>
    <div ng-app="hotelApp" ng-controller="ContentControler">
    <div id="map"></div>
    <h2>Filters</h2>
        <p>Location Name:
            <input type="text" ng-model="location_name">
        </p>
        <p>Maxium Price:
            <input type="text" ng-model="maxPrice">
        </p>
        <p>POI Search Radius:
            <input type="text" ng-model="maxRadius">
        </p>

    	<div id="esra">tese</div>
    	<div id="class" ng-repeat="marker in markers | orderBy : 'title'">
     		 <a href="#" ng-mouseover="goster($event, marker)" ng-mouseleave="gizle($event, marker)">{{marker.title}}-{{marker.deniz}}</a>
        </div>
        <div ng-repeat="x in nas = (names | filter:{prop_Name:location_name} | filter:priceRangeFilter | filter:radiusRangeFilter)"></div>    
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
    </body>
    </html>

但我想用 json 获取 php mysql 数据。如何用 ajax.php 更改 $scope.names 你能帮我吗?

我的 ajax.php 代码:

<?php
$response['success'] = false;
$dsn = "mysql:dbname=dname;host=localhost;charset=utf8;";
$db = new PDO($dsn, "dnames", "1111111");
$stmt = $db->prepare("SELECT * FROM wp_propertiesx");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(!empty($result)) {
	 $response['success'] = true;
	 $response['data'] = $result;
	 $ney = $response['data'];
}

echo json_encode($ney);

?>

【问题讨论】:

    标签: javascript php mysql angularjs json


    【解决方案1】:

    传入的数据必须先用空数组封装在控制器中,进程必须启动,请求完成。简单:

    app.controller('TestCtrl', function ($scope, $http) {
        $scope.names = [];
    
        $scope.operation = function(data) {
            // operation data
        };
    
        $http.get('ajax.php').success(function(data) {
            $scope.names = data;
            for (i = 0; i < $scope.names.length; i++) {
                $scope.operation($scope.names[i]);
            }
        });
    });
    

    【讨论】:

      【解决方案2】:

      首先检查 ajax.php 的结果格式是否正确。比设置所有数据后检查是否应用范围。试试$scope.$apply().

      【讨论】:

        【解决方案3】:

        如果您在调用 php 脚本后没有看到地图更新。首先,确保返回数据。您可以使用 chrome 中的断点或仅使用 console.log(data); 轻松完成此操作。通话后。其次,如果您看到返回的数据并且您将 $scope.names 设置为返回的 json 数据,您可能需要调用 $scope.$apply() 来触发摘要循环并让 $scope 获取新值名称并将其显示在 DOM 中。因此,请在设置 $scope.names 变量后尝试添加以下内容:

        setTimeout(function () {
           $scope.$apply();
        });
        

        如果这确实是您描述的问题,这将触发摘要循环。

        【讨论】:

        • 我必须这样做吗? $http.get('ajax.php').success(function(data) { $scope.names = data; }); setTimeout(function () { $scope.$apply(); });这是行不通的:(
        • 我的 ajax.php 结果:[{"prop_Name":"deniz","prop_Addr":"http:\/\/www.odevi.org\/resim-ekle\/personel\/ 7296\/1484234439_5_7296.jpg","prop_Price":"deneme 1","prop_Dist":"10.00","prop_Desc":"","lat":"36.8582389","lng":"30.631253499999957"},{ "prop_Name":"mehmet","prop_Addr":"http:\/\/www.odevi.org\/resim-ekle\/personel\/7301\/1484299675_52_7301.jpg","prop_Price":"fdfdsf", "prop_Dist":"10.00","prop_Desc":"","lat":"36.1582389","lng":"30.131253499999957"}]
        • setTimeout(function () { $scope.$apply(function () { $http.get('ajax.php').then(function(data) { $scope.names = data; }); }); }, 2000);不工作:(
        • 我注意到您的测试数据 $scope.names 使用属性“long”表示经度,并且从您的服务调用返回的数据使用“lng”作为名称。也许这就是事情失败的地方。确保模拟数据和从服务返回的数据格式相同。如果模拟数据正在工作,那么数据返回以及触发摘要循环应该可以解决问题。干杯
        【解决方案4】:

        当 php-script 返回结果时需要应用范围。首先尝试最小化您的代码以使 ajax 工作正常。之后重新编写代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多