How to send map coordinates to javascript file - with Laravel? - php

I have a contact page. This page contains map information. This map is generated by the script file. How do I change the coordinates dynamically?
Js file content;
var MY_MAPTYPE_ID = 'style_KINESB';
function initialize() {
var featureOpts = [
{
"featureType": "administrative",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#666666"
}
]
},
{
"featureType": 'all',
"elementType": 'labels',
"stylers": [
{ visibility: 'simplified' }
]
},
{
"featureType": "landscape",
"elementType": "all",
"stylers": [
{
"color": "#e2e2e2"
}
]
},
{
"featureType": "poi",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "all",
"stylers": [
{
"saturation": -100
},
{
"lightness": 45
},
{
"visibility": "off"
}
]
},
{
"featureType": "road.highway",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.arterial",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"elementType": "all",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "water",
"elementType": "all",
"stylers": [
{
"color": "#aadaff"
},
{
"visibility": "on"
}
]
}
];
var myGent = new google.maps.LatLng(40.6946703,-73.9280182);
var Kine = new google.maps.LatLng(40.6946703,-73.9280182);
var mapOptions = {
zoom: 11,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.LEFT_TOP,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID,
scaleControl: false,
streetViewControl: false,
center: myGent
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var styledMapOptions = {
name: 'style_KINESB'
};
var image = 'images/resource/mapmarker.png';
var marker = new google.maps.Marker({
position: Kine,
map: map,
animation: google.maps.Animation.DROP,
title: 'B4318, Gumfreston SA70 8RA, United Kingdom',
icon: image
});
var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, customMapType);
}
google.maps.event.addDomListener(window, 'load', initialize);
The area I want to access through the Laravel blade. I want to make the coordinates dynamic.
var myGent = new google.maps.LatLng(40.6946703,-73.9280182);
var Kine = new google.maps.LatLng(40.6946703,-73.9280182);
contact.blade.php
#extends('layouts.frontend.master')
#section('title', 'Empathy - Become Volunteer')
#section('content')
#endsection
Please help me. Thank you very much for your help.

My solution here. I also worked. I'm waiting if you have better solutions.
Firstly. I am add #yield("javascript") directive in master.blade.php file. I add on to the js file.
#yield('javascript')
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAAz77U5XQuEME6TpftaMdX0bBelQxXRlM&callback=initMap" type="text/javascript"></script>
<script src="{{ asset('empathy/frontend/assets/js/googlemaps1.js') }}"></script>
<!-- Custom script for all page -->
<script src="{{ asset('empathy/frontend/assets/js/script.js') }}"></script>
Later edit contact.blade.php
#extends('layouts.frontend.master')
#section('title', 'Empathy - Become Volunteer')
#section('content')
#endsection
#section('javascript')
<script>
var x = JSON.parse('{!! json_encode($coordinate_array[0]) !!}');
var y = JSON.parse('{!! json_encode($coordinate_array[1]) !!}');
</script>
#endsection
ContactPageController.php
$contact = Contact::first();
$coordinate_array = explode(',', $contact->coordinates); // 40.6946703,-73.9280182
This way my solution worked.

Related

geocoder api radar search and multiple markers issue

my script as below. I have to search the pincode and based on search i have to show locations on map
Ques 1: if i have 2 results for same pincode, then also one marker is coming on the map. i want to show seperate markers.
Ques 2: i want to radar search as well using pincode. like if pincode 07201 and 07202 are very near areas then i should get results for both. i tried using radius in my response, but its not working
<script>
var map;
<!-- var marker; -->
function initialize()
{
var mapOptions = {
center: new google.maps.LatLng('40.71338', '-74.193246'),
zoom: 8,
scrollwheel: false,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(40.71338, -74.193246),
map: map,
});
}
jQuery('#searchPincodeForm').submit(function (event) {
event.preventDefault();
var geocoder = new google.maps.Geocoder();
var search_val=$('#country').val();
jQuery.ajax({
type: 'post',
data:{
'pincode':search_val,
},
url: 'searchPincode.php',
success:function(response){
if(response != ''){
$("#result").html(response).show();
geocoder.geocode({
'address': search_val }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
}
})
} else{
$("#result").html("Sorry Dealer not available at this location. For more information please mail at info#movemaxoil.com").show();
}
}
});
});
</script>
Response i get from geocode:
{
"results": [{
"address_components": [{
"long_name": "07108",
"short_name": "07108",
"types": ["postal_code"]
},
{
"long_name": "Newark",
"short_name": "Newark",
"types": ["locality", "political"]
},
{
"long_name": "Essex County",
"short_name": "Essex County",
"types": ["administrative_area_level_2", "political"]
},
{
"long_name": "New Jersey",
"short_name": "NJ",
"types": ["administrative_area_level_1", "political"]
},
{
"long_name": "United States",
"short_name": "US",
"types": ["country", "political"]
}
],
"formatted_address": "Newark, NJ 07108, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 40.73179289999999,
"lng": -74.1830549
},
"southwest": {
"lat": 40.713114,
"lng": -74.21835
}
},
"location": {
"lat": 40.7235275,
"lng": -74.197388
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 40.73179289999999,
"lng": -74.1830549
},
"southwest": {
"lat": 40.713114,
"lng": -74.21835
}
}
},
"place_id": "ChIJK0xWNjlTwokRLb_3zFLt8zM",
"types": ["postal_code"]
}],
"status": "OK"
}
So the issue is here:
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
Your ajax response may contain more than one location point in it, but in the above code you are using only the first location point results[0].geometry.location here. So instead of results[0] you have to loop through all the results array so that multiple points are mapped on your mark.

Custom Google Makers with DataLayer/GeoJson

I'm currently having an Issue getting google markers to display custom images depending on the type. I have had it working in the past that only had one image for all the markers.
map.php
var map,
infoWindow = new google.maps.InfoWindow({pixelOffset: new google.maps.Size(0,-25)});
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {lat: 53.927895, lng: -1.386487}
});
map.data.loadGeoJson('http://customers.auroracomputers.co.uk/customers-json.php');
map.data.addListener('click', function(event) {
infoWindow.setContent(
'Surname: ' + event.feature.getProperty('surname') + '<br>' +
'Postcode: ' + event.feature.getProperty('postcode')
);
var anchor = new google.maps.MVCObject();
anchor.set("position",event.latLng);
infoWindow.open(map,anchor);
});
var iconBase = 'http://customers.auroracomputers.co.uk/icons/'
var icons = {
business: {
icon: iconBase + 'business.png'
},
home: {
icon: iconBase + 'home.png'
},
competitor: {
icon: iconBase + 'devil.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
}
map.data.setStyle({
icon: 'http://customers.auroracomputers.co.uk/icons/home.png',
icon: icons[feature.type].icon,
icon: icon.competitor.icon
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Customer-Json.php
for ($i=0;$i<$nrows;$i++){
$row = mysqli_fetch_assoc($result);
?>
<script>
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [<?echo $row['lng'];?>,<?echo $row['lat'];?>]
},
"properties": {
"surname": "<?echo $row['surname'];?>",
"postcode": "<?echo $row['postcode'];?>",
"type": "<?echo $row['type'];?>"
}
}<?php if( $i != $nrows-1 ){ ?>,<?php } ?>
</script>
GeoJson markers are styled differently than native Google Maps Javascript API v3 markers. See Style GeoJSON Data in the documentation, in particular the section on Change Appearance Dynamically.
map.data.setStyle(function(feature) {
var type = feature.getProperty('type')
return /** #type {google.maps.Data.StyleOptions} */ ({
icon: icons[type].icon,
title: type
});
});
from the reference:
icon Type: string|Icon|Symbol
Icon for the foreground. If a string is provided, it is treated as though it were an Icon with the string as url. Only applies to point geometries.
proof of concept fiddle
code snippet:
var map,
infoWindow = new google.maps.InfoWindow({
pixelOffset: new google.maps.Size(0, -25)
});
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {
lat: 40.7127837,
lng: -74.0059413
}
});
// map.data.loadGeoJson('http://customers.auroracomputers.co.uk/customers-json.php');
map.data.addGeoJson(testGeoJson)
map.data.addListener('click', function(event) {
infoWindow.setContent(
'Surname: ' + event.feature.getProperty('surname') + '<br>' +
'Postcode: ' + event.feature.getProperty('postcode')
);
var anchor = new google.maps.MVCObject();
anchor.set("position", event.latLng);
infoWindow.open(map, anchor);
});
var iconBase = 'http://customers.auroracomputers.co.uk/icons/'
var icons = {
business: {
icon: iconBase + 'business.png'
},
home: {
icon: iconBase + 'home.png'
},
competitor: {
icon: iconBase + 'devil.png'
}
};
map.data.setStyle(function(feature) {
var type = feature.getProperty('type')
return /** #type {google.maps.Data.StyleOptions} */ ({
icon: icons[type].icon,
title: type
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// New York, NY, USA (40.7127837, -74.00594130000002)
// Newark, NJ, USA (40.735657, -74.1723667)
var testGeoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-74.0059413, 40.7127837]
},
"properties": {
"surname": "York",
"postcode": " 10007",
"type": "home"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-74.1723667, 40.735657]
},
"properties": {
"surname": "Newark",
"postcode": "07102",
"type": "business"
}
}]
};
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
One thing I note is the source json is corrupted, hopefully the following might help get that sorted.
<?php
/*
Customer-Json.php
-----------------
The original code had thousands of `<script>` & `</script>` tags
which meant it was not valid json.
I have assumed that the previous loop can be replaced with the
more usual recordset iteration loop as shown below.
Each row has items added to the json array which gets echoed at the
end - there is not need for the script tags at all - just include the
correct headers.
*/
/* store data to be sent */
$json=array();
/* using object notation for ease */
while( $row=mysqli_fetch_object( $result ) ){
$surname=$row->surname;
$postcode=$row->postcode;
$lat=$row->lat;
$lng=$row->lng;
$type=$row->type;
$json[]=array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array( $lng, $lat )
),
'properties' => array(
'surname' => $surname,
'postcode' => $postcode,
'type' => $type
)
);
}
$json=json_encode( $json );
header( 'Content-Type: application/json' );
echo $json;
?>

Google chart showing blank using JSON

I've been trying to get some Google Charts working from some data on a local db. I think I have got the JSON coming out properly now.
{
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
}
And I'm using this as the HTML.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I've gone over it a few times and can't see where I am going wrong.
It occurs since SalesVal column is of number type but the cells contain string values.
According to Format of the Constructor's JavaScript Literal data Parameter:
type [Required] Data type of the data in the column. Supports the
following string values (examples include the v: property, described
later):
'number' - JavaScript number value. Example values: v:7 , v:3.14, v:-55
Having said that you could consider the following options:
Option 1. Modify getData.php endpoint to return a valid json data for google.visualization.DataTable:
"v": "1708.6000" //invalid (current)
"v": 1708.6000 //valid
Option 2
Ensure data column of number type contain JavaScript number value as demonstrated below:
Example
var jsonData = {
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
};
google.load('visualization', '1', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(prepareJsonData(jsonData));
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
function prepareJsonData(json) {
json.rows.forEach(function(row) {
row.c[1].v = parseFloat(row.c[1].v); //ensure number cell value
});
return json;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>

How to add MarkerClusterer to my google map

I'm trying to add the Google Cluster to my map, but i cant work out how to do it? i have created the map and its markers with info box using mysql query in php. know i'm adding more markers they are over lapping so i need to add the cluster command but i can't get it working. my code is below
<script>
$(document).ready(function() {
//------- Google Maps ---------//
// Creating a LatLng object containing the coordinate for the center of the map
var latlng = new google.maps.LatLng(53.0,0);
// Creating an object literal containing the properties we want to pass to the map
var options = {
zoom: 5, // This number can be set to define the initial zoom level of the map
center: latlng,
disableDefaultUI: true,
panControl: false,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP, // This value can be set to define the map type ROADMAP/SATELLITE/HYBRID/TERRAIN
styles: [
{
"featureType": "landscape.natural",
"stylers": [
{ "visibility": "simplified" },
{ "color": "#07c6ee" }
]
},{
"featureType": "landscape.man_made",
"stylers": [
{ "visibility": "on" },
{ "hue": "#6e00ff" },
{ "gamma": 1.96 },
{ "lightness": 18 },
{ "saturation": -78 },
{ "color": "#46fcb3" }
]
},{
"featureType": "water",
"stylers": [
{ "visibility": "simplified" },
{ "color": "#f9ec55" }
]
},{
},{
"featureType": "road.highway",
"stylers": [
{ "visibility": "on" },
{ "color": "#7b8080" }
]
},{
"featureType": "road.arterial",
"stylers": [
{ "visibility": "on" },
{ "color": "#808080" }
]
},{
"featureType": "road.local",
"stylers": [
{ "color": "#808080" },
{ "visibility": "on" }
]
},{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [
{ "color": "#fefffe" },
{ "visibility": "on" }
]
},{
"featureType": "landscape.man_made",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road.highway",
"elementType": "labels.icon",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "poi",
"stylers": [
{ "visibility": "off" }
]
},{
}
]
};
// Calling the constructor, thereby initializing the map
var map = new google.maps.Map(document.getElementById('map_div'), options);
// Define Marker properties
var image1 = new google.maps.MarkerImage('http://www.foodhawkers.co.uk/images/map-market.png',
// This marker is 129 pixels wide by 42 pixels tall.
new google.maps.Size(40, 40),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 18,42.
new google.maps.Point(40, 40)
);
//
// Add Marker
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(51.4636101,-0.1382557),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map, marker1);
});
// Add information window
var infowindow1 = new google.maps.InfoWindow({
content: createInfo('Venn Street Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(51.5367954,-0.0618898),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
// Add information window
var infowindow2 = new google.maps.InfoWindow({
content: createInfo('Broadway Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(51.4721386,-2.7580983),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker3, 'click', function() {
infowindow3.open(map, marker3);
});
// Add information window
var infowindow3 = new google.maps.InfoWindow({
content: createInfo('StrEAT Food Market', '<div style="width:200px">We\'re really hoping to be doing some amazing street food nights in the CENTRE of...</div><br /><br />View profile')
});
var marker4 = new google.maps.Marker({
position: new google.maps.LatLng(51.5945845,-0.1302629),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker4, 'click', function() {
infowindow4.open(map, marker4);
});
// Add information window
var infowindow4 = new google.maps.InfoWindow({
content: createInfo('Alexandra Palace Farmers Market', '<div style="width:200px">Sundays 10:00 - 15:00...</div><br /><br />View profile')
});
var marker5 = new google.maps.Marker({
position: new google.maps.LatLng(51.5050824,-0.0900808),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker5, 'click', function() {
infowindow5.open(map, marker5);
});
// Add information window
var infowindow5 = new google.maps.InfoWindow({
content: createInfo('Borough Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var marker6 = new google.maps.Marker({
position: new google.maps.LatLng(51.5057757,-0.1168251),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker6, 'click', function() {
infowindow6.open(map, marker6);
});
// Add information window
var infowindow6 = new google.maps.InfoWindow({
content: createInfo('The Real Food Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var marker7 = new google.maps.Marker({
position: new google.maps.LatLng(51.5005095,-0.1131232),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker7, 'click', function() {
infowindow7.open(map, marker7);
});
// Add information window
var infowindow7 = new google.maps.InfoWindow({
content: createInfo('Lower Marsh Market', '<div style="width:200px">Lower Marsh is steeped in history as one of London’s oldest and best-loved market streets....</div><br /><br />View profile')
});
var marker8 = new google.maps.Marker({
position: new google.maps.LatLng(51.4682204,-0.0259369),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker8, 'click', function() {
infowindow8.open(map, marker8);
});
// Add information window
var infowindow8 = new google.maps.InfoWindow({
content: createInfo('Brockley Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var marker9 = new google.maps.Marker({
position: new google.maps.LatLng(51.4528397,-0.1019773),
map: map,
icon: image1 // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
});
// Add listener for a click on the pin
google.maps.event.addListener(marker9, 'click', function() {
infowindow9.open(map, marker9);
});
// Add information window
var infowindow9 = new google.maps.InfoWindow({
content: createInfo('Herne Hill Farmers Market', '<div style="width:200px">...</div><br /><br />View profile')
});
var markerCluster = new MarkerClusterer(options, markers);
// Create information window
function createInfo(title, content) {
return '<div class="infowindow"><strong>'+ title +'</strong><br />'+content+'</div>';
}
});
</script>
Which version of MC you are using? Because version 2.0.x has following construct syntax:
var markerCluster = new MarkerClusterer(map, opt_markers, opt_options);
Try this:
var markerCluster = new MarkerClusterer(map);
markerCluster.addMarker(marker1);
...
markerCluster.addMarker(marker9);
Or, keep Your markers in array, add this to top of Your code:
var markers = [];
After declaring each marker add it to that array:
markers.push(markerN);
And add all of them at once to cluster:
markerCluster.addMarkers(markers);

EXTJS JsonStore do not load

I know this will be a repetition. But I have tried my best to solve it, all in vain. I am unable to populate even a simple grid panel!!! Obviously I am a newbie in extjs.
My js code is as follows:
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
url: 'compare.php',
fields: ['name', 'area']
});
store.load();
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: 'Name', width: 100, sortable: true, dataIndex: 'name'},
{header: 'Position', width: 100, sortable: true, dataIndex: 'area'}
],
stripeRows: true,
height:250,
width:500,
title:'DB Grid'
});
grid.render('db-grid');
});
and my php is as follows:
<html>
<head>
</head>
<body bgcolor="white">
<?php
$link = pg_Connect('host=my_host port=5432 dbname=da_name user=postgres password=my_password');
$sql = "SELECT name, area FROM \"TABLE\" LIMIT 10";
if (!$link) {
echo "error";
} else {
$result = pg_query($link, $sql);
$rows = array();
$totaldata = pg_num_rows($result);
while($r = pg_fetch_assoc($result)) {
$rows[] = $r;
}
//echo json_encode($rows);
//echo json_encode(array('country' => $rows));
echo '({"total":"'.$totaldata.'","country":'.json_encode($rows).'})';
}
?>
</body>
</html>
And my json is as follows:
[
{
"total": "10",
"country": [
{
"name": "CULTIV",
"area": "1.10584619505971e-006"
},
{
"name": "CULTIV",
"area": "2.87818068045453e-006"
},
{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},
{
"name": "CULTIV",
"area": "1.17171452984621e-007"
},
{
"name": "CULTIV",
"area": "1.25584028864978e-006"
},
{
"name": "CULTIV",
"area": "5.86309965910914e-007"
},
{
"name": "CULTIV",
"area": "4.12220742873615e-007"
},
{
"name": "CULTIV",
"area": "7.59690840368421e-006"
},
{
"name": "CULTIV",
"area": "2.47360731009394e-007"
},
{
"name": "CULTIV",
"area": "4.04940848284241e-005"
}
]
Do I need to set any proxy for this? Actually my application is running on different server than my database.
I have no experience in PostgreSQL but I advice you to use pg_fetch_object() function instead of pg_fetch_assoc() in that case.
Try something like this:
while($obj = $result->pg_fetch_object()) {
$rows = $obj;
}
echo '({"total":"'.$totaldata.'","country":'.json_encode($rows).'})';
Your JSON is malformed. Ext.data.JsonReader (automatically configured when you use a JsonStore) expects a JSON object with a root node, defined in your reader config. The reader should throw an exception if the root is undefined.
So define a root for your JsonReader:
var store = new Ext.data.JsonStore({
url: 'compare.php',
root: 'country', // required!
fields: ['name', 'area']
});
And your JSON should look like this:
{
"total": 10,
"country": [{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},{
...
}]
}

Categories