call json location ajax google maps - google-maps-api-3

i have json data loction like this {"name":"Tiesna","latitude":"123456","longitude":"9876543","posisi":"cirebon","waktu":"2015-07-01 21:49:52"}{"name":"Jastin","latitude":"-1234567","longitude":"987654","posisi":"susukan","waktu":"2015-07-01 23:11:52"}
i want to call to google maps for location
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 50,
center: new google.maps.LatLng(-39.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1],
locations[i][2]),
map: map
});

I'm still having a little trouble understanding exactly what you are asking, but hopefully this will help...
If you have a JS object like the following
var loc1 = {"name":"Tiesna","latitude":"33.890542","longitude":"151.274856"};
you can push the relevant properties to your array with something like the following:
var locations = [];
locations.push([loc1.name, loc1.latitude, loc1.longitude]);

Related

Draw airline flight map using Google Map APIs

I am trying to draw an airline flight map using Google Map APIs. But I got some issues in generating polylines between every two points. So far, it only returns one polyline of the very first two points. I could not find any error so far. Is there anything wrong with the last for loop? Any comments and help will be highly appreciated!
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 41.871314, lng: -99.869580},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var Lat = [42.365843,37.756066,47.450431,28.431450,38.898793,34.040667];
var Lng = [-71.009625,-122.440175,-122.308806,-81.308094,-77.037227,-118.289537];
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var Poly = new Array();
for (var i = 0; i<Lat.length; i++) {
var pos = new google.maps.LatLng(Lat[i],Lng[i]);
Poly.push(pos);
};
for (var j = 0; j<Poly.length; j++) {
if (j%2 == 0){
var poly = new Array();
poly = Poly.slice(j,j+2);
var flowline = new google.maps.Polyline({
path: poly,
geodesic: true,
strokeColor: "#DC143C",
strokeOpacity: .8,
strokeWeight: 2,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
});
}
};
flowline.setMap(map);
}
You are only setting the map property of the last polyline. This is outside of the loop that creates the polylines:
flowline.setMap(map);
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 41.871314,
lng: -99.869580
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var Poly = new Array();
for (var i = 0; i < Lat.length; i++) {
var pos = new google.maps.LatLng(Lat[i], Lng[i]);
Poly.push(pos);
}
var flowlineNonGeodesic = new google.maps.Polyline({
path: Poly,
geodesic: false,
strokeColor: "#00FF00",
strokeOpacity: .8,
strokeWeight: 2,
map: map
});
for (var j = 0; j < Poly.length; j++) {
if (j % 2 == 0) {
var poly = Poly.slice(j, j + 2);
var flowline = new google.maps.Polyline({
path: poly,
geodesic: true,
strokeColor: "#DC143C",
strokeOpacity: .8,
strokeWeight: 2,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
});
flowline.setMap(map);
}
}
}
google.maps.event.addDomListener(window, "load", initMap);
var Lat = [42.365843, 37.756066, 47.450431, 28.431450, 38.898793, 34.040667];
var Lng = [-71.009625, -122.440175, -122.308806, -81.308094, -77.037227, -118.289537];
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

How to add a random point inside a polygon in Google Maps?

I have a bounds to a place and created a polygon of that place.
How can I generate a random point inside the bounds of that polygon?
One way of doing it. This will calculate the bounds of the polygon, then guess a random point inside that bounds, if the point is contained by the polygon, it will put a marker there.
// calculate the bounds of the polygon
var bounds = new google.maps.LatLngBounds();
for (var i=0; i < polygon.getPath().getLength(); i++) {
bounds.extend(polygon.getPath().getAt(i));
}
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
// Guess 100 random points inside the bounds,
// put a marker at the first one contained by the polygon and break out of the loop
for (var i = 0; i < 100; i++) {
var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
var point = new google.maps.LatLng(ptLat,ptLng);
if (google.maps.geometry.poly.containsLocation(point,polygon)) {
var marker = new google.maps.Marker({position:point, map:map});
break;
}
}
working fiddle
working fiddle with up to 100 random points
var polygon;
function initialize() {
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 4,
center: new google.maps.LatLng(22.7964, 79.8456),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var coords =
[
new google.maps.LatLng(18.979026,72.949219), //Mumbai
new google.maps.LatLng(28.613459,77.255859), //Delhi
new google.maps.LatLng(22.512557,88.417969), //Kolkata
new google.maps.LatLng(12.940322,77.607422) //Bengaluru
];
polygon = new google.maps.Polygon({
paths: coords,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
polygon.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (var i=0; i < polygon.getPath().getLength(); i++) {
bounds.extend(polygon.getPath().getAt(i));
}
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
for (var i = 0; i < 100; i++) {
var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
var point = new google.maps.LatLng(ptLat,ptLng);
if (google.maps.geometry.poly.containsLocation(point,polygon)) {
var marker = new google.maps.Marker({position:point, map:map});
var infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent(marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
break;
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="width: 530px; height: 500px">
</div>

Google Maps getBounds() returns undefined

I'm writing a code which will:
-- Load a map and center it on a KML
-- Draw a polygon based on the bounds of the map.
Here below the code. I get an error
Uncaught TypeError: Cannot call method 'getNorthEast' of undefined
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
}
Any Suggestion?
Thanks,
Daniele
You need to put all the code that depends on the map bounds inside the event listener.
var surface = null;
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
google.maps.event.addListener(map,'bounds_changed', function()
{
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
}); // end of listener callbck
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
} // end of initialize

Center map and zoom to fit the markers on the screen

I have the following code to detect the visitors GPS position and show it on the Google Maps JavaScript v3 map. Everything works as I want it but the code will not center or zoom as I want - it simple use the standard position (right over Asia)! I want it to fit the markers on the map.
var rendererOptions = {
draggable: false
};
if(navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
} else {
alert('Din webbläsare stödjer inte någon geologisk lokalisering med hjälp av HTML5');
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var marker_gps;
var map_gps;
var options_gps;
function displayPosition(position) {
/***********************
** GPS-POSITION **
************************/
directionsDisplay = new google.maps.DirectionsRenderer();
localStorage.coor = position.coords.latitude.toFixed(6) + ',' + position.coords.longitude.toFixed(6);
var gps_coor = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
if(typeof(marker) != 'undefined') marker.setMap(null);
localStorage.accuracy = position.coords.accuracy;
document.getElementById('accuracy').innerHTML = number_format(localStorage.accuracy) + ' meter';
directionsDisplay.setMap(map_gps);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
marker_gps = new google.maps.Marker({
position: gps_coor,
draggable: false,
map: map_gps
});
var circle_gps = new google.maps.Circle({
center: gps_coor,
radius: position.coords.accuracy,
map: map_gps,
fillColor: '#3333ff',
fillOpacity: 0.2,
strokeColor: '#3333ff',
strokeOpacity: 0.5,
strokeWeight: 1
});
/*****************************
** FÄRDSÄTT (DISTANS) **
******************************/
var start = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
var stop = new google.maps.LatLng(<?php echo $photo['coordinates_latitude'].','.$photo['coordinates_longitude']; ?>);
var request = {
origin: start,
destination: stop,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK) {
var distance = (response.routes[0].legs[0].distance.value / 1000).toFixed(0);
var duration = secondsToString(response.routes[0].legs[0].duration.value);
document.getElementById('distance').innerHTML = 'Cirka ' + distance + ' kilometer';
document.getElementById('duration').innerHTML = 'Cirka ' + duration;
directionsDisplay.setDirections(response);
}
});
}
function initialize_gps() {
var coor = new google.maps.LatLng(localStorage.coor);
var bounds = new google.maps.LatLngBounds();
options_gps = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: google.maps.LatLng(localStorage.coor),
streetViewControl: false
}
map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
map_gps.fitBounds(bounds);
}
function secondsToString(seconds) {
var numdays = Math.floor(seconds / 86400);
var numhours = Math.floor((seconds % 86400) / 3600);
var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
return (numdays != 0 ? (numdays == 1 ? '1 dag' : numdays + ' dagar') + ', ' : '')
+ (numhours != 0 ? (numhours == 1 ? '1 timme' : numhours + ' timmar') + (numdays != 0 ? ', ' : ' och ') : '')
+ (numminutes != 0 ? (numminutes == 1 ? '1 minut' : numminutes + ' minuter') : '');
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert('Error: ' + errors[error.code]);
}
How can I make this to work?
Thanks in advance.
EDIT
Here's the edited part of the initialize_gps function. This part didn't work - nothing new happened. It just center the map over Asia like before.
function initialize_gps() {
var coor = new google.maps.LatLng(localStorage.coor);
var bounds = new google.maps.LatLngBounds();
options_gps = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: google.maps.LatLng(localStorage.coor),
streetViewControl: false
}
map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
map_gps.fitBounds(bounds);
}
EDIT
I have copy-pasted the whole code to jsFiddle. Link: http://jsfiddle.net/edgren/WRxt4/
The general solution to fitting the map display to a set of markers is to add them to an empty google.maps.LatLngBounds object (by calling bounds.extend), then calling map.fitBounds with that bounds.
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (let i = 0; i < beaches.length; i++) {
const beach = beaches[i];
var marker = new google.maps.Marker({
position: { lat: beach[1], lng: beach[2] },
map,
title: beach[0],
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: { lat: 0, lng: 0 },
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
const beaches = [
["Bondi Beach", -33.890542, 151.274856, 4],
["Coogee Beach", -33.923036, 151.259052, 5],
["Cronulla Beach", -34.028249, 151.157507, 3],
["Manly Beach", -33.80010128657071, 151.28747820854187, 2],
["Maroubra Beach", -33.950198, 151.259302, 1],
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (let i = 0; i < beaches.length; i++) {
const beach = beaches[i];
var marker = new google.maps.Marker({
position: { lat: beach[1], lng: beach[2] },
map,
title: beach[0],
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Complex Marker Icons</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>

The markers don't appear on GMAP

Google Maps Demo
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
for (var i = 0; i < locations.length; i++) {
var image = new google.maps.MarkerImage('marker' + i + 'images/13.png',
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var location = locations[i];
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: location[0],
zIndex: location[3]
});
}
}
</script>
I'm using WAMPSERVER, and I store my 13.png under images folder (www/tacking/images/13.png). I put my .php file under www/tracking/testing.php. Did I put my path correctly?
Please guide me...
In this line:
var image = new google.maps.MarkerImage('marker' + i + 'images/13.png'
You are looking for a marker at: 'marker' + i + 'images/13.png'
Which will be something like: markerNimages/13.png
Looks like that's not where you have the PNG file right? You say you have put it in images/13.png. How about you just get rid of the 'marker' + i ?

Resources