I was wondering if it is possible to get the places of interest in a location based on the lattitude/longitude information or approximate street address gathered from a GPS system?
places of interest are defined in this context as: Restaurants, Resorts, Parks, malls, movie theaters, etc.
Are there some online services either with bing maps / google maps / something else, that provides such information in some parsed format?
Thank you
On the client side, you use the Google AJAX Search API to search for places of interest around a specific coordinate:
<!DOCTYPE html>
<html>
<head>
<title>Google AJAX Search API Demo</title>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1');
var localSearch;
function localSearchComplete() {
// Check that we got results
if (localSearch.results && localSearch.results.length > 0) {
// Loop through our results, printing them to the page.
var results = localSearch.results;
document.getElementById('content').innerHTML = "";
for (var i = 0; i < results.length; i++) {
document.getElementById('content').innerHTML +=
'<div style="clear: both;">' +
'<div style="float: left; width: 160px;">' + results[i].title + '</div>' +
'<div style="float: left; width: 80px;">' + results[i].lat + '</div>' +
'<div style="float: left; width: 80px;">' + results[i].lng + '</div>' +
'<div style="float: left; width: 140px;">' + results[i].streetAddress + '</div>' +
'<div style="float: left; width: 120px;">' + results[i].city + '</div>' +
'</div>';
}
}
}
function OnLoad() {
localSearch = new google.search.LocalSearch();
// Coordinates for "New York, NY"
localSearch.setCenterPoint("40.70, -74.00");
localSearch.setSearchCompleteCallback(this, localSearchComplete, null);
localSearch.execute("restaurants");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial; font-size: 11px;">
<div id="content">Loading...</div>
</body>
</html>
The result would be the following:
Local Search Results http://img693.imageshack.us/img693/240/localsearch.png
To get the same results from the server side in JSON format, you may want to check the following article:
Google AJAX Search API: Flash and other Non-Javascript Environment
Basically you would be able to issue a request to Google in the following format:
http://ajax.googleapis.com/ajax/services/search/local?v=2.0&q=restaurants+40.70,-74.00
Which would return the following JSON:
{
"responseData": {
"results": [
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.703684",
"lng": "-73.994861",
"accuracy": "8",
"title": "The River Cafe",
"titleNoFormatting": "The River Cafe",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "1 Water Street",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40703684\u0026Point.longitude_e6\u003d-73994861\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d9181090609208620883",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 522-5200"
}
],
"addressLines": [
"1 Water Street",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.702956",
"lng": "-73.994105",
"accuracy": "8",
"title": "Pete\u0026#39;s Downtown \u003cb\u003eRestaurant\u003c/b\u003e",
"titleNoFormatting": "Pete's Downtown Restaurant",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "1 Cadman Plaza West",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40702956\u0026Point.longitude_e6\u003d-73994105\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d4933341782274549162",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 858-3510"
}
],
"addressLines": [
"1 Cadman Plaza West",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.702726",
"lng": "-73.993499",
"accuracy": "8",
"title": "Grimaldi\u0026#39;s Pizzeria",
"titleNoFormatting": "Grimaldi's Pizzeria",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "19 Old Fulton St",
"city": "",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40702726\u0026Point.longitude_e6\u003d-73993499\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d4244157563901397553",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 858-4300"
}
],
"addressLines": [
"19 Old Fulton St",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.695108",
"lng": "-73.996252",
"accuracy": "8",
"title": "Teresa\u0026#39;s \u003cb\u003eRestaurant\u003c/b\u003e",
"titleNoFormatting": "Teresa's Restaurant",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "80 Montague Street",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40695108\u0026Point.longitude_e6\u003d-73996252\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d12686375620276309855",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 797-3996"
}
],
"addressLines": [
"80 Montague Street",
"Brooklyn, NY"
]
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
}
],
"estimatedResultCount": "189307",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/local?oe\u003dutf8\u0026ie\u003dutf8\u0026num\u003d4\u0026mrt\u003dyp%2Cloc\u0026sll\u003d37.779160%2C-122.420090\u0026start\u003d0\u0026hl\u003den\u0026q\u003drestaurants+40.70%2C-74.00"
},
"viewport": {
"center": {
"lat": "40.699396",
"lng": "-73.99675"
},
"span": {
"lat": "0.010291",
"lng": "0.007801"
},
"sw": {
"lat": "40.69425",
"lng": "-74.00065"
},
"ne": {
"lat": "40.70454",
"lng": "-73.99285"
}
}
},
"responseDetails": null,
"responseStatus": 200
}
The Google AJAX Search API documentation provides some code snippets that demonstrate API access in Java, PHP, Python, Perl and Flash.
Related
Is it possible to increase de accracy / precision of the Geocoder JSON response?
I could accomplish it using the Map, however, with the Geocoder It wasn't possible.
Problem Description
Using Mapbox Geocoder for JS:
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.min.js"></script>
With the Tutorial Use the geocoder without a map:
https://docs.mapbox.com/mapbox-gl-js/example/mapbox-gl-geocoder-no-map/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Use the geocoder without a map</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.min.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.css" type="text/css">
<style>
#geocoder {
z-index: 1;
margin: 20px;
}
.mapboxgl-ctrl-geocoder {
min-width: 100%;
}
</style>
<div id="geocoder"></div>
<pre id="result"></pre>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiaGVldm8iLCJhIjoiY2t2bWZkZXVqNXkzcjJvcXB0MHZyeTV1ZiJ9.d-C9xDxy9sNFiiN4klZl_w';
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
types: 'country,region,place,postcode,locality,neighborhood'
});
geocoder.addTo('#geocoder');
// Get the geocoder results container.
const results = document.getElementById('result');
// Add geocoder result to container.
geocoder.on('result', (e) => {
results.innerText = JSON.stringify(e.result, null, 2);
});
// Clear results container when search is cleared.
geocoder.on('clear', () => {
results.innerText = '';
});
</script>
</body>
</html>
I receive a JSON response with lots of data, that I can configure with some options before sending the request. However, I couldn't find an option to increase the accuracy / precision of this response on the following documentation:
https://github.com/mapbox/mapbox-gl-geocoder/blob/main/API.md
The JSON Response has only 6 decimal digits, as can be seen on the Mapbox website example below and is not reliable to make calculations of close distances.
{
"type": "FeatureCollection",
"query": [
"825",
"s",
"milwaukee",
"ave",
"deerfield",
"il",
"60015"
],
"features": [{
"id": "address.4356035406756260",
"type": "Feature",
"place_type": [
"address"
],
"relevance": 1,
"properties": {},
"text": "Milwaukee Ave",
"place_name": "825 Milwaukee Ave, Deerfield, Illinois 60015, United States",
"matching_text": "South Milwaukee Avenue",
"matching_place_name": "825 South Milwaukee Avenue, Deerfield, Illinois 60015, United States",
"center": [
-87.921434,
42.166602
],
"geometry": {
"type": "Point",
"coordinates": [
-87.921434,
42.166602
],
"interpolated": true,
"omitted": true
},
"address": "825",
"context": [{
"id": "neighborhood.287187",
"text": "Lake Cook Road"
},
{
"id": "postcode.13903677306297990",
"text": "60015"
},
{
"id": "place.5958304312090910",
"wikidata": "Q287895",
"text": "Deerfield"
},
{
"id": "region.3290978600358810",
"short_code": "US-IL",
"wikidata": "Q1204",
"text": "Illinois"
},
{
"id": "country.9053006287256050",
"short_code": "us",
"wikidata": "Q30",
"text": "United States"
}
]
},
{
"id": "address.7464624790403620",
"type": "Feature",
"place_type": [
"address"
],
"relevance": 0.5,
"properties": {},
"text": "Milwaukee Ave",
"place_name": "825 Milwaukee Ave, Wheeling, Illinois 60090, United States",
"matching_text": "South Milwaukee Avenue",
"matching_place_name": "825 South Milwaukee Avenue, Wheeling, Illinois 60090, United States",
"center": [
-87.910299,
42.144504
],
"geometry": {
"type": "Point",
"coordinates": [
-87.910299,
42.144504
],
"interpolated": true
},
"address": "825",
"context": [{
"id": "neighborhood.287187",
"text": "Lake Cook Road"
},
{
"id": "postcode.9418633295906190",
"text": "60090"
},
{
"id": "place.9902190947082220",
"wikidata": "Q935043",
"text": "Wheeling"
},
{
"id": "region.3290978600358810",
"short_code": "US-IL",
"wikidata": "Q1204",
"text": "Illinois"
},
{
"id": "country.9053006287256050",
"short_code": "us",
"wikidata": "Q30",
"text": "United States"
}
]
},
{
"id": "address.6472754353404224",
"type": "Feature",
"place_type": [
"address"
],
"relevance": 0.5,
"properties": {},
"text": "Milwaukee Avenue",
"place_name": "825 Milwaukee Avenue, Glenview, Illinois 60025, United States",
"matching_text": "South Milwaukee Avenue",
"matching_place_name": "825 South Milwaukee Avenue, Glenview, Illinois 60025, United States",
"center": [
-87.852677,
42.071152
],
"geometry": {
"type": "Point",
"coordinates": [
-87.852677,
42.071152
]
},
"address": "825",
"context": [{
"id": "neighborhood.275266",
"text": "Northfield Woods"
},
{
"id": "postcode.3787740186211610",
"text": "60025"
},
{
"id": "place.10211845459386970",
"wikidata": null,
"text": "Glenview"
},
{
"id": "region.3290978600358810",
"short_code": "US-IL",
"wikidata": "Q1204",
"text": "Illinois"
},
{
"id": "country.9053006287256050",
"short_code": "us",
"wikidata": "Q30",
"text": "United States"
}
]
},
{
"id": "address.1225436500189372",
"type": "Feature",
"place_type": [
"address"
],
"relevance": 0.5,
"properties": {},
"text": "Milwaukee Ave",
"place_name": "825 Milwaukee Ave, Buffalo Grove, Illinois 60089, United States",
"matching_text": "South Milwaukee Avenue",
"matching_place_name": "825 South Milwaukee Avenue, Buffalo Grove, Illinois 60089, United States",
"center": [
-87.917484,
42.158084
],
"geometry": {
"type": "Point",
"coordinates": [
-87.917484,
42.158084
],
"interpolated": true
},
"address": "825",
"context": [{
"id": "neighborhood.287187",
"text": "Lake Cook Road"
},
{
"id": "postcode.11727721238210580",
"text": "60089"
},
{
"id": "place.8589721255665070",
"wikidata": "Q967086",
"text": "Buffalo Grove"
},
{
"id": "region.3290978600358810",
"short_code": "US-IL",
"wikidata": "Q1204",
"text": "Illinois"
},
{
"id": "country.9053006287256050",
"short_code": "us",
"wikidata": "Q30",
"text": "United States"
}
]
},
{
"id": "address.240107872738130",
"type": "Feature",
"place_type": [
"address"
],
"relevance": 0.5,
"properties": {},
"text": "Milwaukee Avenue",
"place_name": "825 Milwaukee Avenue, Wheeling, Illinois 60090, United States",
"matching_text": "South Milwaukee Avenue",
"matching_place_name": "825 South Milwaukee Avenue, Wheeling, Illinois 60090, United States",
"center": [
-87.898319,
42.126289
],
"geometry": {
"type": "Point",
"coordinates": [
-87.898319,
42.126289
],
"interpolated": true,
"omitted": true
},
"address": "825",
"context": [{
"id": "neighborhood.287189",
"text": "Milwaukee Avenue"
},
{
"id": "postcode.9418633295906190",
"text": "60090"
},
{
"id": "place.9902190947082220",
"wikidata": "Q935043",
"text": "Wheeling"
},
{
"id": "region.3290978600358810",
"short_code": "US-IL",
"wikidata": "Q1204",
"text": "Illinois"
},
{
"id": "country.9053006287256050",
"short_code": "us",
"wikidata": "Q30",
"text": "United States"
}
]
}
],
"attribution": "NOTICE: © 2018 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."
}
Precision of 6 decimal places gives you ~10 centimeter accuracy. Mapbox is using GeoJSON specification which has following recommendation about precision:
The size of a GeoJSON text in bytes is a major interoperability
consideration, and precision of coordinate values has a large impact
on the size of texts. A GeoJSON text containing many detailed
Polygons can be inflated almost by a factor of two by increasing
coordinate precision from 6 to 15 decimal places. For geographic
coordinates with units of degrees, 6 decimal places (a default common
in, e.g., sprintf) amounts to about 10 centimeters, a precision well
within that of current GPS systems. Implementations should consider
the cost of using a greater precision than necessary.
GPS-enabled smartphones are typically accurate to within a 4.9 m (16 ft.) radius under open sky. However, their accuracy worsens near buildings, bridges, and trees.ref
Here is a demo of distance accuracy when precision of 6 decimal places is used:
var lat1, lat2, lon1, lon2;
//https://www.geeksforgeeks.org/program-distance-two-points-earth/
// JavaScript program to calculate Distance Between Two Points on Earth
function distance(lat1, lat2, lon1, lon2) {
// The math module contains a function
// named toRadians which converts from
// degrees to radians.
lon1 = lon1 * Math.PI / 180;
lon2 = lon2 * Math.PI / 180;
lat1 = lat1 * Math.PI / 180;
lat2 = lat2 * Math.PI / 180;
// Haversine formula
let dlon = lon2 - lon1;
let dlat = lat2 - lat1;
let a = Math.pow(Math.sin(dlat / 2), 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.pow(Math.sin(dlon / 2), 2);
let c = 2 * Math.asin(Math.sqrt(a));
// Radius of earth is 6371 kilometers
let km = c * 6371; //kilometers
let mi = c * 3956; //miles
// calculate the result
return [(km), (mi), (km * 1000), (km * 100000)];
}
function update() {
lat1 = document.getElementById('lat1').value;
lat2 = document.getElementById('lat2').value;
lon1 = document.getElementById('lon1').value;
lon2 = document.getElementById('lon2').value;
let result = distance(lat1, lat2, lon1, lon2);
format('result1', ...result);
}
update();
function format(id, km, mi, m, cm) {
document.getElementById(id).innerHTML =
`Centimeters:\t${cm}\n` +
`Meters:\t\t${m}\n` +
`Kilometers:\t${km}\n` +
`Miles:\t\t${mi}\n`;
}
format('result2', ...distance(42.167803, 42.144516, -87.921589, -87.910345));
body {
margin: 0;
padding: 1rem;
}
input {
width: 110px;
font-size: 16px;
color: red;
}
.result {
width: 400px;
height: 5rem;
background-color: wheat;
font-size: 16px;
white-space: pre;
}
<p>Change values to update result.</p>
<label for="lat1">Latitude A:</label>
<input type="number" id="lat1" name="lat1" value="0.000000" step="0.000001" onchange="update()">
<label for="lon1">Longitude A:</label>
<input type="number" id="lon1" name="lon1" value="0.000000" step="0.000001" onchange="update()">
<br>
<label for="lat2">Latitude B:</label>
<input type="number" id="lat2" name="lat2" value="0.000001" step="0.000001" onchange="update()">
<label for="lon2">Longitude B:</label>
<input type="number" id="lon2" name="lon2" value="0.000000" step="0.000001" onchange="update()">
<div id="result1" class="result"></div>
<hr>
<p>(42.167803, -87.921589) to (42.144516, -87.910345) distance:</p>
<div id="result2" class="result"></div>
You can verify the above distance on Google Maps.
If you search "Illinois, United States" you get coordinates -89.2749461071049 40.1492928594. May be it's related to how they collect data. They collect data from open data sources, such as OpenStreetMap and NASA, and from purchased proprietary data sources, such as DigitalGlobe.ref. To verify, you can add new marker/location with more accurate coordinates and see if the APIs returns only 6 digits or entire provided coordinates.
I've made a map calling multiple data points from my json file I've managed to display an image as a marker and get a label to display but my issue is with the label how do I add style to it without it breaking my map or messing with the coordinates?
Currently, the first label works and is in the right place but the second way I'm trying to initialise it doesn't even work and as far as my research has shown that how it has to be laid out to add style.
tried adding style to the initial label stopped the whole map from displaying.
tried adding a label in the formative seen can't even get the text to display
//stores Google Map object and the JSON called from PHP
var map;
var locations;
var markers;
function initMap() {
// creates the map and puts it in the html giving its zoom and position
map = new google.maps.Map(document.getElementById('map'),
{
center: {
lat: 51.0590282,
lng: -1.3104568},
zoom: 9
});
$.getJSON(
//URL for my php script
'http://up858296.ct.port.ac.uk/ParkRun/ParkrunJson.php',
function(jsonData) {
// putting jason data under variable location
locations = jsonData;
locations.forEach(
function(loc) {
// gets objects which arent in my JSON
loc.map = map;
if (loc.gender == "Male") {
loc.icon.url = 'Man.png';
} else {
loc.icon.url = 'Women.png';
}
loc.icon.scaledSize = new google.maps.Size(40, 40);
loc.icon.labelOrigin = new google.maps.Point(10, 50);
loc.title = "Parkrun: " + loc.parkrun + ", Runner: " + loc.name + ", Time: " + loc.duration;
//fist label that displays but cant add style
loc.label = loc.name + ", Time:" + loc.duration;
//creates marker on google map named "loc"
// "loc" stores lat, lng ect
var marker = new google.maps.Marker(loc);
// Add listener for a click event upon which will open url for parkrun sites.
marker.addListener(
'click',
function() {
window.open(loc.link);
}
);
//initialise styled map label overlay (second lable wont even display text)
/*var m = new google.maps.Marker({
position: loc,
label: {
text: loc.name + ", Time:" + loc.duration,
color: 'white',
fontWeight: 'bold',
},
})*/
}
);
}
);
};
This works for me (using the formatting from your second attempt for the label defined in the first).
loc.icon.scaledSize = new google.maps.Size(40, 40);
loc.icon.labelOrigin = new google.maps.Point(10, 50);
loc.title = "Parkrun: " + loc.parkrun + ", Runner: " + loc.name + ", Time: " + loc.duration;
loc.label = {
text: loc.name + ", Time:" + loc.duration,
color: 'white',
fontWeight: 'bold',
};
proof of concept fiddle
code snippet:
var map;
var locations;
var markers;
function initMap() {
// creates the map and puts it in the html giving its zoom and position
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 51.0590282,
lng: -1.3104568
},
zoom: 9,
mapTypeId: 'satellite'
});
// putting jason data under variable location
locations = jsonData;
locations.forEach(
function(loc) {
// gets objects which arent in my JSON
loc.map = map;
if (loc.gender == "Male") {
loc.icon.url = 'http://maps.google.com/mapfiles/ms/micons/blue.png';
} else {
loc.icon.url = 'http://maps.google.com/mapfiles/ms/micons/red.png';
}
loc.icon.scaledSize = new google.maps.Size(40, 40);
loc.icon.labelOrigin = new google.maps.Point(10, 50);
loc.title = "Parkrun: " + loc.parkrun + ", Runner: " + loc.name + ", Time: " + loc.duration;
loc.label = {
text: loc.name + ", Time:" + loc.duration,
color: 'white',
fontWeight: 'bold',
};
var marker = new google.maps.Marker(loc);
// Add listener for a click event upon which will open url for parkrun sites.
marker.addListener('click', function() {
window.open(loc.link);
});
});
}
jsonData = [{
"position": {
"lat": 51.1699,
"lng": -0.8371
},
"gender": "Male",
"parkrun": "Alice Holt",
"name": "James Baker",
"duration": "16:57:00",
"link": "https:\/\/www.parkrun.org.uk\/aliceholt\/",
"icon": []
}, {
"position": {
"lat": 51.2193,
"lng": -1.5052
},
"gender": "Male",
"parkrun": "Andover",
"name": "John Kane",
"duration": "18:13:00",
"link": "https:\/\/www.parkrun.org.uk\/andover\/",
"icon": []
}, {
"position": {
"lat": 51.2599,
"lng": -1.0824
},
"gender": "Male",
"parkrun": "Basingstoke",
"name": "Matthieu Marshall",
"duration": "16:51:00",
"link": "https:\/\/www.parkrun.org.uk\/basingstoke\/",
"icon": []
}, {
"position": {
"lat": 50.8084,
"lng": -1.6414
},
"gender": "Male",
"parkrun": "Brockenhurst",
"name": "James Bewley",
"duration": "18:06:00",
"link": "https:\/\/www.parkrun.org.uk\/brockenhurst\/",
"icon": []
}, {
"position": {
"lat": 50.9705,
"lng": -1.3731
},
"gender": "Male",
"parkrun": "Eastleigh",
"name": "Tom Bray",
"duration": "18:06:00",
"link": "https:\/\/www.parkrun.org.uk\/eastleigh\/",
"icon": []
}, {
"position": {
"lat": 50.8483,
"lng": -1.166
},
"gender": "Women",
"parkrun": "Fareham",
"name": "Leslie Ellul",
"duration": "52:00:00",
"link": "https:\/\/www.parkrun.org.uk\/fareham\/",
"icon": []
}, {
"position": {
"lat": 50.8733,
"lng": -0.9753
},
"gender": "Women",
"parkrun": "Havant",
"name": "Nicola Ellul",
"duration": "26:10:00",
"link": "https:\/\/www.parkrun.org.uk\/havant\/",
"icon": []
}, {
"position": {
"lat": 51.1188,
"lng": -0.8766
},
"gender": "Male",
"parkrun": "Hogmoor Inclosure",
"name": "James Kingston",
"duration": "17:07:00",
"link": "https:\/\/www.parkrun.org.uk\/hogmoorinclosure\/",
"icon": []
}, {
"position": {
"lat": 50.8009,
"lng": -1.2035
},
"gender": "Male",
"parkrun": "Lee-on-the-Solent",
"name": "Jack Porter",
"duration": "18:24:00",
"link": "https:\/\/www.parkrun.org.uk\/leeonthesolent\/",
"icon": []
}, {
"position": {
"lat": 50.7506,
"lng": -1.547
},
"gender": "Male",
"parkrun": "Lyminghton Woodside",
"name": "Callum Johnson",
"duration": "18:39:00",
"link": "https:\/\/www.parkrun.org.uk\/lymingtonwoodside\/",
"icon": []
}, {
"position": {
"lat": 50.8685,
"lng": -1.3427
},
"gender": "Male",
"parkrun": "Netley Abbey",
"name": "Samuel Skinner",
"duration": "18:24:00",
"link": "https:\/\/www.parkrun.org.uk\/netleyabbey\/",
"icon": []
}, {
"position": {
"lat": 50.8405,
"lng": -1.0776
},
"gender": "Male",
"parkrun": "Portsmouth Lakeside",
"name": "Liam Dunne",
"duration": "16:18:00",
"link": "https:\/\/www.parkrun.org.uk\/portsmouthlakeside\/",
"icon": []
}, {
"position": {
"lat": 50.9651,
"lng": -0.9754
},
"gender": "Male",
"parkrun": "Queen Elizabeth",
"name": "Grant Hopkins",
"duration": "19:33:00",
"link": "https:\/\/www.parkrun.org.uk\/queenelizabeth\/",
"icon": []
}, {
"position": {
"lat": 51.265,
"lng": -0.7547
},
"gender": "Male",
"parkrun": "Rushmoor",
"name": "Kim Bowling",
"duration": "17:18:00",
"link": "https:\/\/www.parkrun.org.uk\/rushmoor\/",
"icon": []
}, {
"position": {
"lat": 50.9245,
"lng": -1.4096
},
"gender": "Male",
"parkrun": "Southampton",
"name": "Peter Hart",
"duration": "16:49:00",
"link": "https:\/\/www.parkrun.org.uk\/southampton\/",
"icon": []
}, {
"position": {
"lat": 50.7787,
"lng": -1.082
},
"gender": "Male",
"parkrun": "Southsea",
"name": "Adam Barlow",
"duration": "16:31:00",
"link": "https:\/\/www.parkrun.org.uk\/southsea\/",
"icon": []
}, {
"position": {
"lat": 50.8847,
"lng": -1.2472
},
"gender": "Male",
"parkrun": "Whiteley",
"name": "Richard Waldron",
"duration": "15:46:00",
"link": "https:\/\/www.parkrun.org.uk\/whiteley\/",
"icon": []
}, {
"position": {
"lat": 51.0662,
"lng": -1.3126
},
"gender": "Male",
"parkrun": "Winchester",
"name": "Marley Godden",
"duration": "17:59:00",
"link": "https:\/\/www.parkrun.org.uk\/winchester\/",
"icon": []
}];
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
I am having quite a hard time accessing data from an api call and having it shown on Mapbox. I am able to have one marker shown on the map, while I should have 10 markers. I think I am doing something wrong with ng-repeat, but I am not sure what. Any help would be appreciated.
Here is a link to view the full JSON response from the API call http://jsonblob.com/55e734cee4b01190df374f1e
// index.html
<div ng-repeat="venue in bars.venues">
<marker lat="{{venue.location.lat}}" lng="{{venue.location.lng}}">
<h1>{{venue.name}}</h1>
<p>{{venue.contact}}</p>
<p>{{venue.location.formattedAddress}}</p>
</marker>
</div>
// app.js
$http.get(url)
.then(function (response) {
$scope.bars = response.data.response;
});
// sample data from api
{
"meta": {
"code": 200,
"requestId": "55e72707498e3d9a002d7bc4"
},
"response": {
"venues": [
{
"id": "42c1e480f964a520c4251fe3",
"name": "The View",
"contact": {
"phone": "4158961600",
"formattedPhone": "(415) 896-1600"
},
"location": {
"address": "55 4th St",
"crossStreet": "at Marriott Marquis",
"lat": 37.78510950100554,
"lng": -122.40469515323639,
"distance": 29,
"postalCode": "94103",
"cc": "US",
"city": "San Francisco",
"state": "CA",
"country": "United States",
"formattedAddress": [
"55 4th St (at Marriott Marquis)",
"San Francisco, CA 94103",
"United States"
]
},
"categories": [
{
"id": "4bf58dd8d48988d1d5941735",
"name": "Hotel Bar",
"pluralName": "Hotel Bars",
"shortName": "Hotel Bar",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/travel/hotel_bar_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 12634,
"usersCount": 9499,
"tipCount": 121
},
"url": "http://www.sfviewlounge.com",
"hasMenu": true,
"menu": {
"type": "Menu",
"label": "Menu",
"anchor": "View Menu",
"url": "https://foursquare.com/v/the-view/42c1e480f964a520c4251fe3/menu",
"mobileUrl": "https://foursquare.com/v/42c1e480f964a520c4251fe3/device_menu"
},
So I figured out why only one marker was showing. I was previously using angular google maps and had ngMaps as a module. After I deleted it, all my markers showed.
I'm trying to loop through all this array data but it won't work out how to display it all via jquery using the .each function? Can someone help me out?
ARRAY:
{
"ListOrdersResult": {
"Orders": {
"Order": [
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
},
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
}
]
},
"CreatedBefore": "2014-05-14T01:12:05Z"
},
"ResponseMetadata": {
"RequestId": "46f5c980-91e6-44d3-bc9d-668976855862"
},
"xmlns": "https://mws.amazonservices.com/Orders/2011-01-01"
}
CURRENT JS:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.Orders.Order, function(index, value) {
console.log(value);
console.log(value.ShipmentServiceLevelCategory);
});
$('body').text(JSON.stringify(newOrders));
});
});
You are missing the first element of the JSON object:
Change
$.each(newOrders.Orders.Order, function(index, value) {
To
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
Demo:
http://jsfiddle.net/9YU3H/
I'm using the foursquare venues API to populate a select menu and list in my web app. I'd like to sort the venues alphabetically by name.
Here is a JSON response from the foursquare API, which has some venues:
[ { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4c6ee03fb5a5236a74744b52", "name": "Peninsular Paper Dam", "contact": {}, "location": { "address": "1265 Leforge Rd", "crossStreet": "at Huron River Rd", "lat": 42.256628, "lng": -83.623933, "distance": 892, "postalCode": "48198", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d165941735", "name": "Scenic Lookout", "pluralName": "Scenic Lookouts", "shortName": "Scenic Lookout", "icon": { "prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/sceniclookout_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 31, "usersCount": 12, "tipCount": 0 }, "likes": { "count": 0, "groups": [] }, "specials": { "count": 0, "items": [] }, "photos": { "count": 2, "groups": [] } } }, { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4ba58202f964a520cb0d39e3", "name": "Benito's Pizza", "contact": { "phone": "7349610707", "formattedPhone": "(734) 961-0707" }, "location": { "address": "1088 N Huron River Dr", "lat": 42.256532, "lng": -83.629082, "distance": 1035, "postalCode": "48197", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d1ca941735", "name": "Pizza Place", "pluralName": "Pizza Places", "shortName": "Pizza", "icon": { "prefix": "https://foursquare.com/img/categories_v2/food/pizza_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 50, "usersCount": 34, "tipCount": 0 }, "url": "http://www.benitospizza.com/", "likes": { "count": 0, "groups": [] }, "menu": { "type": "foodAndBeverage", "url": "https://foursquare.com/v/benitos-pizza/4ba58202f964a520cb0d39e3/menu", "mobileUrl": "https://foursquare.com/v/4ba58202f964a520cb0d39e3/device_menu" }, "specials": { "count": 0, "items": [] }, "photos": { "count": 0, "groups": [] } } } ]
I'm able to parse this response with this code:
for (var i = 0; i < venues.length; i++) {
name = venues[i]['venue']['name'];
category = venues[i]['venue']['categories'][0]['name'];
icon = venues[i]['venue']['categories'][0]['icon']['prefix'];
icon = icon.slice(0, -1); // remove trailing "_" character
icon = icon + venues[i]['venue']['categories'][0]['icon']['suffix'];
address = venues[i]['venue']['location']['address'];
city = venues[i]['venue']['location']['city'];
state = venues[i]['venue']['location']['state'];
distance_meters = venues[i]['venue']['location']['distance'];
distance_miles = distance_meters / 1609.34;
distance_miles = Math.round(distance_miles*100)/100;
x = 1; // in the product use i for index below
HTMLmarkupList += "<li><img src=\"" + icon + "\" class=\"ui-li-thumb\" style=\"margin: 23px 10px\" onerror=\"ImgError(this);\">" + "<h3 style=\"margin-left: -40px\">" + name + "</h3><p style=\"margin-left: -40px\">" + category + "</p><p style=\"margin-left: -40px\">" + address + ", " + city + ", " + state + "</p><p style=\"margin-left: -40px\">" + distance_miles + " miles from you.</p></li>";
HTMLmarkupSelect += "<option value\"" + i + "\">" + name + "</option>";
}
Right now, the value of the select is just i, but as I'll be needing to store other variables along with the name in my database I may update the value in each select option to include things like the address, city, state, etc.... I mention this because if I was only using the name in the select, I could just build an array of names and use the javascript sort method.
Can anyone help with how to sort the venues alphabetically by name? Thanks.
Information:
http://www.w3schools.com/jsref/jsref_sort.asp
Example:
venues.sort(function(a,b){
if(a.venue.name == b.venue.name) return 0;
return (a.venue.name < b.venue.name) ? -1 : 1;
});