Converting .JSON list to google maps - php

Hi I have a aircraft json list on a pi connected to a home network that I would like to convert to a google maps format similar to flightradar24.com etc. I have tried multiple ways but have not got very far. Any help would be good I am only a beginner with coding so excuse the not so good explanation. Thanks :)
{ "now" : 1497814126.3,
"messages" : 20531195,
"aircraft" : [
{"hex":"c82089","squawk":"5625","flight":"ANZ519 ","altitude":3250,"vert_rate":3008,"track":79,"speed":225,"messages":88,"seen":69.0,"rssi":-24.9},
{"hex":"c81881","squawk":"0262","flight":"ANZ101 ","lat":-36.881150,"lon":174.829440,"nucp":7,"seen_pos":0.3,"altitude":9725,"vert_rate":3136,"track":269,"speed":330,"messages":1360,"seen":0.1,"rssi":-8.1},
{"hex":"aae597","squawk":"0767","flight":"AAL83 ","lat":-36.149918,"lon":175.464592,"nucp":7,"seen_pos":0.4,"altitude":23400,"vert_rate":-1792,"track":212,"speed":386,"messages":1734,"seen":0.1,"rssi":-24.8},
{"hex":"c81dd5","squawk":"0256","flight":"QFA140 ","lat":-36.892043,"lon":174.183456,"nucp":7,"seen_pos":0.0,"altitude":21800,"vert_rate":2240,"track":270,"speed":398,"messages":4023,"seen":0.0,"rssi":-27.1},
{"hex":"c8178c","squawk":"0260","flight":"ANZ937 ","lat":-36.605002,"lon":173.758772,"nucp":6,"seen_pos":52.9,"altitude":26675,"vert_rate":1152,"track":295,"speed":412,"messages":4913,"seen":1.4,"rssi":-32.3}
]
}

Here is a demo that shows how to view latitude/longitude data as markers on a map
var data = [{
"hex": "c82089",
"squawk": "5625",
"flight": "ANZ519 ",
"altitude": 3250,
"vert_rate": 3008,
"track": 79,
"speed": 225,
"messages": 88,
"seen": 69.0,
"rssi": -24.9
},
{
"hex": "c81881",
"squawk": "0262",
"flight": "ANZ101 ",
"lat": -36.881150,
"lon": 174.829440,
"nucp": 7,
"seen_pos": 0.3,
"altitude": 9725,
"vert_rate": 3136,
"track": 269,
"speed": 330,
"messages": 1360,
"seen": 0.1,
"rssi": -8.1
},
{
"hex": "aae597",
"squawk": "0767",
"flight": "AAL83 ",
"lat": -36.149918,
"lon": 175.464592,
"nucp": 7,
"seen_pos": 0.4,
"altitude": 23400,
"vert_rate": -1792,
"track": 212,
"speed": 386,
"messages": 1734,
"seen": 0.1,
"rssi": -24.8
},
{
"hex": "c81dd5",
"squawk": "0256",
"flight": "QFA140 ",
"lat": -36.892043,
"lon": 174.183456,
"nucp": 7,
"seen_pos": 0.0,
"altitude": 21800,
"vert_rate": 2240,
"track": 270,
"speed": 398,
"messages": 4023,
"seen": 0.0,
"rssi": -27.1
},
{
"hex": "c8178c",
"squawk": "0260",
"flight": "ANZ937 ",
"lat": -36.605002,
"lon": 173.758772,
"nucp": 6,
"seen_pos": 52.9,
"altitude": 26675,
"vert_rate": 1152,
"track": 295,
"speed": 412,
"messages": 4913,
"seen": 1.4,
"rssi": -32.3
}
];
function initMap() {
var myLatLng = {
lat: -36.363,
lng: 175.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: myLatLng
});
for (var i = 0; i < data.length; i++) {
var flight = data[i],
latLng = new google.maps.LatLng(flight.lat, flight.lon);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.flight
});
}
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIPPUQ0PSWMjTsgvIWRRcJv3LGfRzGmnA&callback=initMap">
</script>
<div id="map"></div>

Related

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

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.

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.

Client-side JSON decode jQuery [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please view my other question here
I am trying to work out how to decode a JSON response from a PHP file.
The JSON is structured as follows:
[{
"id": 1,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
"price": " - "
}
}, {
"id": 2,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
"price": "\u00a3 50 "
}
}, {
"id": 3,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
"price": "\u00a3 50 "
}
}, {
"id": 4,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
"price": " - "
}
}, {
"id": 5,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
"price": "\u00a3 50 "
}
}, {
"id": 6,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
"price": "\u00a3 200 "
}
}, {
"id": 7,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
"price": "\u00a3 9 "
}
}, {
"id": 8,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
"price": "\u00a3 100 "
}
}, {
"id": 9,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
"price": "\u00a3 40 "
}
}, {
"id": 10,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
"price": "\u00a3 10 "
}
}, {
"id": 11,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
"price": " - "
}
}, {
"id": 12,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
"price": "\u00a3 30 "
}
}, {
"id": 13,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
"price": "\u00a3 31 "
}
}, {
"id": 14,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
"price": "\u00a3 25 "
}
}, {
"id": 15,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
"price": "\u00a3 1.0k "
}
}, {
"id": 16,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
"price": "\u00a3 15 "
}
}, {
"id": 17,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
"price": "\u00a3 21 \/hr"
}
}, {
"id": 18,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
"price": "\u00a3 12 "
}
}, {
"id": 19,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
"price": "\u00a3 20 \/hr"
}
}, {
"id": 20,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
"price": "\u00a3 7 \/hr"
}
}]
You can view the current AJAX call on my other question (Link at top of this post).
Could anyone shed some light on how I would decode the JSON array client-side?
I'd like to have a structure like this:
<div class="item">
<div class="title">JSON Title</div>
<div class="price">JSON Price</div>
</div>
Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.
If you always expect json :
$.ajax({ url: ..., data: ...,
dataType: 'json', // <- tell jQuery to expect json,
// and to build a js object from the answer
success : function(obj){
//obj is a regular js object, built from the received json
obj[i].info.title; // <- accessing this piece of data
}
});
If your data is sometimes json, sometimes something else :
success: function(data){
var obj
try {
obj = JSON.parse(data);
// if no exception is thrown, data was a valid json string,
// and obj is a regular js object
obj[i].info.title; // <- accessing this piece of data
} catch (e) {
// Maybe do something on error ?
};
}
You can then build a html string like hsuk suggested :
var html = '';
for(i=0; i < obj.length; i++) {
html += '<div class="item">';
html += '<div class="title">' + obj[i].info.title + '</div>';
html += '<div class="price">' + obj[i].info.price + '</div>';
html += '</div>';
}
alert.html(html).fadeIn();
This is how you do it. What you need is JSON.parse()
test.php
<?php
// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
exit(json_encode(array(
array(
'id' => 1,
'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
),
array(
'id' => 2,
'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
),
array(
'id' => 3,
'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
)
)));
}
?>
<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Make Ajax Request
$.get("test.php?loadData", function(data)
{
// Parse Data
var jsonResults = JSON.parse(data);
// Iterate Through Results
$.each(jsonResults, function(key, value)
{
// Display Data
$('.results').append(
'<div class="item" id="'+ value.info.id +'">'+
'<div class="title">'+ value.info.title +'</div>'+
'<div class="price">'+ value.info.price +'</div>'+
'</div>'
);
});
});
});
</script>
<!-- HTML Page - Display Result -->
<div class="results"></div>
Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.
Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:
var myObject = {"foo": "bar"};
or
var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);
But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)

Javascript delete JSON elements

I have this JSON string in a PHP page:
{
"elements": [{
"type": "pie",
"alpha": 0.3,
"animate": [{
"type": "fade"
}, {
"type": "bounce",
"distance": 5
}],
"start-angle": 0,
"tip": "#val# de #total# #percent#",
"colours": ["#d01f3c", "#356aa0", "#C79810"],
"values": [{
"value": 1,
"label": "procesador amd sempron 140"
}, {
"value": 1,
"label": "procesador sempron le130"
}, {
"value": 1,
"label": "procesador amd a4-3300 x2"
}, {
"value": 1,
"label": "procesador intel celeron g530"
}]
}],
"title": {
"text": "Procesadores, Reinicio",
"style": "color: #356aa0; font-size: 20px"
},
"bg_colour": "#FFFFFF",
"x_axis": null
}
I call it like this:
$.getJSON("restart_proce.php", function(json)
{
console.log(json);
I need to transform it to this:
[{\"value\": 1, \"label\": \"procesador amd sempron 140\" }, { \"value\": 1, \"label\": \"procesador sempron le130\" }, { \"value\": 1, \"label\": \"procesador amd a4-3300 x2\" }, { \"value\": 1, \"label\": \"procesador intel celeron g530\" } ]
I'm trying to delete elements like this:
delete json.elements[3];
but it doesn't delete anything. How can I make it work?
Removing an item from an Array:
There are several ways. The splice method is the most versatile:
data.items.splice(3, 1); // Removes three items starting with the 2nd,
splice modifies the original array, and returns an array of the items you removed.
Try this:
json.elements.splice(3, 1);
See: Array.splice
Just modify the values directly before console.log(json)
json= json.elements[0].values
Or in the restart_proce.php php page just echo
echo json_encode($data['elements'][0]['values']); // if associative array is used.
Try this:
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"hitesh.prajapati#phptalent.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result);
delete data.result[3];
alert(data.result);
working JSFiddle
or You can use splice to remove elements from an array.

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