Trying to plot the markers on google map using GeoJSON - javascript

I am trying to print markers on "google maps" using "geojson" for a given input coordinates.Below attached is the JSON file.
{
"type": "FeatureCollection",
"features":[{
"type":"Feature",
"geometry":
{
"type":"Point",
"coordinates":[-117.7431667,35.9595,0.01]
}
}
]
My Specific problem is i got 3 parameters in the "coordinates" section present.I have referred to couple of examples where the "coordinates" have got two parameters.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('mapDisplay'), {
zoom: 8,
center: new google.maps.LatLng(44.5403, -78.5463),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$("#button3").click(function(){
$.get("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21",
function(data,status){
console.info("test");
$.each(data.features, function (i, obj) {
$.each(obj.geometry, function (ind, obj) {
if(ind=="coordinates")
console.log("key:" + ind + " value:" + obj);
var coords = obj;
var latLng = new google.maps.LatLng(coords[2],coords[1],coords[0]);
var marker = new google.maps.Marker
({
position: latLng,
icon: iconBase + 'schools_maps.png',
map: map
});
});
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
<body>
<div id="mapDisplay">
</div>
<div id="button_Display">
<button id="button1">Sesimic Events last week</button>
</div>
<div id="Sesimic_Events">
<button id="button2">Places affected</button>
</div>
<div id="markers">
<button id="button3">GoogleMarkers</button>
</div>
<div id="result">
</div>
Any help would be highly appreciated.
Below attached is the screenshot of the output i got when i ran "googlemarkers" button

I think you overcomplicate this task. Read about the GeoJSON Detail Format here -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson_detail.php
Each item of the features section of the JSON response is always on the format :
{
type: "Feature",
properties: {
//a LOT of properties ...
},
geometry: {
type: "Point",
coordinates: [
longitude, //<-- you need this
latitude, //<-- and this
depth
]
},
id: String
}
So plotting the earthquake markers is straight forward :
$.get("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21", function(data,status){
var latLng, marker;
$.each(data.features, function(i, obj) {
latLng = new google.maps.LatLng(
parseFloat(obj.geometry.coordinates[1]),
parseFloat(obj.geometry.coordinates[0])
)
marker = new google.maps.Marker({
position: latLng,
map: map
})
})
})
your code simplified and working here -> http://jsfiddle.net/9p9pk3je/

For loading and parsing GeoJSON data you could utilize Data API, the following example demonstrates how to load GeoJSON data and place markers:
Example
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
map.data.addListener('addfeature', function (o) {
setMarker(map, o.feature);
});
map.data.loadGeoJson("http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-10-14&endtime=2015-10-21");
}
function setMarker(map, feature) {
var latLng = feature.getGeometry().get();
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=drawing&callback=initMap"
async defer></script>

Related

Google Maps & Turf.js Polyline Integration

I am working on an example google maps and turf js integration. I added the line with GeoJson data.Working snippet is attached. But I want to create a polyline out of turf line positions.
for (var j = 0; j < line.geometry.coordinates.length; j++) {
var wp = new google.maps.LatLng(line.geometry.coordinates[j][1], line.geometry.coordinates[j][0])
path.push(wp);
}
I tried to create a path then create my polyline based on this path but couldn't manage to create a path out of turf line arrays.
Any ideas how can I do this?
Thanks in advance!
var path = [];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
maxZoom: 8,
minZoom: 1,
center: {
lat: 0,
lng: -180
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var line = {
"type": "Feature",
"properties": { "line": "on" },
"geometry": {
"type": "LineString",
"coordinates": [
[-122.214, 37.772],
[-157.821, 21.291],
[178.431, -18.142],
[153.027, -27.467]
]
}
};
map.data.addGeoJson(line);
var point = turf.point([185.431, -4.542]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.geometry.coordinates[1], point.geometry.coordinates[0]),
map: map,
});
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://npmcdn.com/#turf/turf#4.7.2/turf.min.js"></script>
<div id="map"></div>
You need to create a polyline and add it to the map:
var polyline = new google.maps.Polyline({
path: path
});
polyline.setMap(map);
I solved it, I just didn't see it...
$.each(line.geometry.coordinates, function (key) {
var wp = { lat: line.geometry.coordinates[key][1], lng: line.geometry.coordinates[key][0] }
path.push(wp);
});

Google Maps JavaScript API markers & infowindows

I'm facing an issue with the open method on infoWindow object.
I want to set all my map utility objects dynamically but when the open method is called it raises me an error because the infoWindow object associated is undefined.
Here is my code :
// Markers & infoWindows
var markers = [];
var infoWindows = [];
for(var i=0; i<myList.length; i++) {
markers.push(
new google.maps.Marker({
position: myList[i].coord,
map: map,
title: myList[i].city
})
);
infoWindows.push(
new google.maps.InfoWindow({
content: myList[i].address
})
);
markers[i].addListener('click', function() {
infoWindows[i].open(map, markers[i]);
});
}
[ Where myList is just an arry of JSON formated objects. ]
All the markers and infoWindows are well set. I can access their properties and print them to the console.
But as I said the infoWindows[i] is typed undefined so the open method isn't found. A contrario I can access and print the content attribute of this infoWindows[i] object. Seems weird to me...
If someone is able to explain me I will be happy :)
Related question: Google Maps JS API v3 - Simple Multiple Marker Example
When the loop completes i is left at infoWindows.length, which is past the end of the array. One way to fix it is with function closure on i:
markers[i].addListener('click', (function(i) {
return function() {
infoWindows[i].open(map, markers[i]);
}}(i)));
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
// Markers & infoWindows
var markers = [];
var infoWindows = [];
for (var i = 0; i < myList.length; i++) {
markers.push(
new google.maps.Marker({
position: myList[i].coord,
map: map,
title: myList[i].city
})
);
infoWindows.push(
new google.maps.InfoWindow({
content: myList[i].address
})
);
markers[i].addListener('click', (function(i) {
return function() {
infoWindows[i].open(map, markers[i]);
}
}(i)));
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var myList = [{
coord: {
lat: 42,
lng: -72
},
city: "Somewhere",
address: "Somewhere"
}, {
coord: {
lat: 40.7127837,
lng: -74.0059413
},
city: "New York, NY, USA",
address: "New York, NY, USA"
}, {
coord: {
lat: 40.735657,
lng: -74.1723667
},
city: "Newark, NJ, USA",
address: "Newark, NJ, USA"
}];
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>

Trying to parse external json file to create markers in google maps api

I am using JavaScript and a external JSON file.
Here is my JSON file. It is in the same folder as my js file. I called the JSON file csus_locations.JSON
{
"locations": [
{
"latitude": 38.558961,
"longitude": -121.423011,
"name": "AIRC",
"title": "THIS IS WHERE STUFF GETS DONE!"
},
{
"latitude": 38.562605,
"longitude": -121.419683,
"name": "GUY WEST",
"title": "PRESIDENT?"
},
{
"latitude": 38.556652,
"longitude": -121.423842,
"name": "well",
"title": "WORKOUT"
},
{
"latitude": 38.555465,
"longitude": -121.422551,
"name": "Hornetsatdium",
"title": "FOOTBAL!"
}
]}
I Know that this is legal json code because i tested to verify it. But can i remove "locations": and remove the brackets to make it simpler to parse into google maps?
I am trying to parse the json file using $http.get but my i am note sure if i wrote the code correctly
angular.module('app.controllers', ['ionic'])
.controller('mapCtrl', function ($scope, $ionicSideMenuDelegate, $ionicLoading, $compile, $ionicPopup, $http) {
$ionicSideMenuDelegate.canDragContent(false);
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Sac State'
});
//i want to get parse with $http.get but i am not sure if i wrote this code correctly
$http.get('csus_locations.json').success(function(res){
console.log("success!");
$scope.locations = res.locations;
//window.alert("The app is reading the Json file!"); this was a test to see if the get function was working
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
});
/* this was my first attempt to create markers
console.log(jsonCSUS);
angular.forEach(jsonCSUS, function(value, key){
var latLng_csus = new google.maps.LatLng(value.latitude, value.longitude);
var marker = new google.maps.Marker({
position: latLng_csus,
title: value.name
});
marker.setMap(map);
});*/
var onSuccess = function (position) {
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
});
The provided JSON file, indeed is a valid one, so you could initialize markers like this:
$http.get('csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
Working example
angular.module('mapApp', ['ionic'])
.controller('mapCtrl', function ($scope, $http) {
var mapOptions = {
center: new google.maps.LatLng(38.5602, -121.4241),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
$http.get('https://gist.githubusercontent.com/vgrem/c7ec78e7078c2c9ed1c3/raw/959e9d8b8e60544fcc169ea890e84a2624ed8bbb/csus_locations.json').success(function (data) {
$scope.locations = data.locations;
$scope.locations.forEach(function(item){
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: item.name,
map: map
});
});
});
});
#map-canvas {
width: 800px;
height: 600px;
}
<link href="http://code.ionicframework.com/1.1.1/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.1.1/js/ionic.bundle.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true"></script>
<div ng-app="mapApp" ng-controller="mapCtrl">
<div id="map-canvas"></div>
</div>

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in {array}

This is the script I'm using.
<script>
var user_lat, user_lng;
var map;
var url = "./rest/network";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 17,
lng: 80
},
zoom: 5
});
$.post(url,function(data,successStatus){
$.each(data, function(index, value) {
new google.maps.Marker({
position: value,
draggable: false,
map: map,
title: "cab"
});
});
});
}
</script>
The url returns [{lat:12.74711089,lng:79.98483278},{lat:18.0,lng:80.0},{lat:19.0,lng:78.0}]
Again when I use this code its working
<script>
var user_lat, user_lng;
var map;
var url = "./rest/network";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 17,
lng: 80
},
zoom: 5
});
var data = [{lat:12.74711089,lng:79.98483278},
{lat:18.0,lng:80.0},
{lat:19.0,lng:78.0}];
$.each(data, function(index, value) {
new google.maps.Marker({
position: value,
draggable: false,
map: map,
title: "cab"
});
});
}
</script>
If the array format is the problem, then the second code also shouldn't work. But it is working. I'm not knowing the reason behind the problem. Is there any problem with the ajax call?

I have a trouble in setting up gmaps.js in my google ap

i have some trouble in implementing this multiple input pin in google map
THE ERROR "cannot call method 'setContextMenu' is undefined
does anyone know how i am going to fixed it
var map;
function initialize() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(10.2833, 123.9000)
};
map.setContextMenu({
control: 'map',
options: [{
title: 'Add marker',
name: 'add_marker',
action: function(e) {
this.addMarker({
lat: e.latLng.lat(),
lng: e.latLng.lng(),
title: 'New marker'
});
}
}, {
title: 'Center here',
name: 'center_here',
action: function(e) {
this.setCenter(e.latLng.lat(), e.latLng.lng());
}
}]
});
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
you need to initialize map before using it. move this call down map.setContextMenu below the line that you initialize the map map = new google.maps.Map(
//first initialize the map
map = new google.maps.Map( //...
//now it is safe to use
map.setContextMenu({

Categories

Resources