How to build this product with google maps? - google-maps

I want to build an exact replica of a website with a different landmark to point towards.
Could you please tell me what I should learn in order to do it please ?
So far, I've created this and don't know what to do next :
https://jsfiddle.net/hasnain721/01v7s2m4/6/
I am a very basic coder btw!
Thanks in advance!
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3478, -6.2597),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//infoWindow.setPosition(pos);
// infoWindow.setContent('<b>You are here.</b><br><b>Lat:</b> '+position.coords.latitude+'<br><b>Lon:</b> '+position.coords.longitude);
map.setCenter(pos);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: String(pos.lat) + ", " + String(pos.lng),
});
//draws out the path from current location to landmark
var flightPlanCoordinates = [{
lat: position.coords.latitude,
lng: position.coords.longitude
},
{
lat: 21.4224779,
lng: 39.8251832
}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
//draws out the path from current location to landmark
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}

You need to change the coordinates of the "flightPlanCoordinates" variable.
sample pointing at the Statue of Liberty :
var flightPlanCoordinates = [
{lat: position.coords.latitude, lng: position.coords.longitude},
{lat: 40.689249, lng: -74.0445}
];

Related

How do I highlight a road on a Google map?

I wish to highlight a Google map of Lincoln, NE. according to regions defined by the Multiple Listing Services (MLS) map of the city. This region map can be found here:
http://www.lincolnrealtors.com/pdf/MLS_Area_Map
I can construct simple polygons for example hightlighting region 31 in the diagram above using:
// Define the LatLng coordinates for the polygon's path.
var Region31 = [
{lat:40.813614, lng: -96.682262},
{lat: 40.813484, lng: -96.644154},
{lat: 40.788145, lng: -96.644154},
{lat: 40.8027, lng: -96.682348},
{lat: 40.813614, lng: -96.682262}
];
But those are only lines when in reality, the MLS regions are delineated in terms of actual highways. For example, region 31 has its lower border along "Normal Blvd" which is not a straight line as you can see by looking at the Google map.
Is there a means of highlighting a particular length of highway in Google Maps and if so, could someone explain this or suggest a reference?
Thanks,
Dominic
You can use the DirectionsService to return polylines that follow the roads.
proof of concept fiddle (I needed to adjust some of your points to avoid the directions service adding extra turns)
code snippet:
var geocoder;
var map;
// Define the LatLng coordinates for the polygon's path.
var Region31 = [{
lat: 40.813436,
lng: -96.682268
}, {
lat: 40.813363,
lng: -96.644167
}, {
lat: 40.788145,
lng: -96.644154
}, {
lat: 40.8027,
lng: -96.682348
}, {
lat: 40.813435,
lng: -96.682267
}];
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();
for (var i = 0; i < Region31.length; i++) {
var marker = new google.maps.Marker({
position: Region31[i],
map: map,
draggable: true
});
bounds.extend(marker.getPosition());
var directionsService = new google.maps.DirectionsService();
directionsService.route({
origin: Region31[i],
destination: Region31[(i + 1) % Region31.length],
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true
})
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
The only api came in my mind is Polyline.

google maps live tracking issue with Polylines

I'm trying to start a live tracking via google maps fetching new locations from a database via ajax and it works fine but the problem is with drawing Polylines I get this error "InvalidValueError: at index 0: not a LatLng or LatLngLiteral: not an Object" which means the "line" variable value can't be used as a point as in here google maps link. Here's the code
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
$.post('ajax/track.php',{car:'1'}).done(function (data) {
var parsed = JSON.parse(data);
var lat = parsed.lat,
lon = parsed.lon;
var newPoint = new google.maps.LatLng(lat,lon);
var line = "{lat: "+lat+", lng: "+lon+"},";
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
var flightPlanCoordinates = [
];
flightPlanCoordinates.push(line);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
else {
marker = new google.maps.Marker({
position: newPoint,
map: map,
icon: 'images/1.png',
});
}
map.setCenter(newPoint);
});
setTimeout(autoUpdate, 5000);
}
autoUpdate();
UPDATE as suggested by #geocodezip:
var line = {lat: lat, lng: lon};
I got this error "InvalidValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number" so I changed it into
var line = {lat: parseFloat(lat), lng: parseFloat(lon)};
in console I get the last location only not an array of locations
The error is telling you that this:
var line = "{lat: "+lat+", lng: "+lon+"},";
Is not a google.maps.LatLng or a google.maps.LatLngLiteral, because it isn't, it is a string.
This would be a valid google.maps.LatLngLiteral:
var line = {lat: lat, lng: lon};
proof of concept fiddle
code snippet:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
var initlat = 42;
var initlon = -72;
var increment = 0.001;
var count = 0;
var flightPlanCoordinates = [];
function autoUpdate() {
/* $.post('ajax/track.php', {
car: '1'
}).done(function(data) { */
data = JSON.stringify({
lat: +(initlat + increment * count),
lon: +(initlon + increment * count)
});
// data = "{lat:" + (initlat + increment * count) + ",lon:" + (initlon + increment * count) + "}";
count++;
var parsed = JSON.parse(data);
var lat = parsed.lat,
lon = parsed.lon;
var newPoint = new google.maps.LatLng(lat, lon);
// var line = "{lat: " + lat + ", lng: " + lon + "},";
var line = {
lat: lat,
lng: lon
};
flightPlanCoordinates.push(line);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
} else {
marker = new google.maps.Marker({
position: newPoint,
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
}
map.setCenter(newPoint);
// });
setTimeout(autoUpdate, 5000);
}
autoUpdate();
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>

Why google map Polyline not showing (in Chrome)?

I use google map to show markers,
then I want to use polyline to link markers one by one.
but polyline doesn't showing.
my code as below:
$(document).ready(function (){
/*map initial*/
var mapOptions = {
...
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
/*draw markers*/
var tmp_user_location1 = new google.maps.LatLng(37.772,-122.214);
var tmp_marker1 = new google.maps.Marker({
position: tmp_user_location1,
map: map
});
var tmp_user_location2 = new google.maps.LatLng(21.291,-157.821);
var tmp_marker2 = new google.maps.Marker({
position: tmp_user_location2,
map: map
});
arr_markers.push(tmp_marker1);
arr_markers.push(tmp_marker2);
/*draw polyline*/
arr_user_location_polyline.push(tmp_user_location1);
arr_user_location_polyline.push(tmp_user_location2);
var user_location_path = new google.maps.Polyline({
paths: arr_user_location_polyline,
geodesic: true,
strokeColor: "#FF00FF",
strokeOpacity: 1.0,
strokeWeight: 2
});
user_location_path.setMap(map);
}
screen capture picture
any one help?
thanks a lot.
The issue with your code is that a google.maps.PolylineOptions object doesn't have a paths property (a google.maps.Polygon does), it has a path property.
var user_location_path = new google.maps.Polyline({
path: arr_user_location_polyline,
geodesic: true,
strokeColor: "#FF00FF",
strokeOpacity: 1.0,
strokeWeight: 2
});
If I fix that, and the javascript errors in the posted code:
Uncaught ReferenceError: arr_markers is not defined
Uncaught ReferenceError: arr_user_location_polyline is not defined
I get a polyline: proof of concept fiddle
code snippet:
$(document).ready(function() {
var arr_markers = [];
var arr_user_location_polyline = [];
/*map initial*/
var mapOptions = {
center: {
lat: 21.291,
lng: -157.821
},
zoom: 3
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
/*draw markers*/
var tmp_user_location1 = new google.maps.LatLng(37.772, -122.214);
var tmp_marker1 = new google.maps.Marker({
position: tmp_user_location1,
map: map
});
var tmp_user_location2 = new google.maps.LatLng(21.291, -157.821);
var tmp_marker2 = new google.maps.Marker({
position: tmp_user_location2,
map: map
});
arr_markers.push(tmp_marker1);
arr_markers.push(tmp_marker2);
/*draw polyline*/
arr_user_location_polyline.push(tmp_user_location1);
arr_user_location_polyline.push(tmp_user_location2);
var user_location_path = new google.maps.Polyline({
path: arr_user_location_polyline,
geodesic: true,
strokeColor: "#FF00FF",
strokeOpacity: 1.0,
strokeWeight: 2
});
user_location_path.setMap(map);
});
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

How to determine if a point K(lat,lng) is on a simple polyline from A(lat,lng) to B(lat,lng) in Google Map [duplicate]

This question already has an answer here:
Detect if google map marker is placed on route
(1 answer)
Closed 7 years ago.
I have a polyline in google maps from point A(lat,lng) to B(lat,lng). If someone gives me a point K(lat,lng) and say that it is on the polyline from A (lat,lng) to B(lat,lng) or B(lat,lng) to A(lat,lng) then how can I determine it is true? I am thinking about something as the following :
if A.lat <= K.lat AND B.lat >= K.lat OR B.lat <= K.lat AND A.lat >= K.lat then
K is on the line
else
K is not on the line
Should this logic work? I am asking because in my test, mostly it worked but some rare cases it did not work even though the point was actually taken from the line.
NB : Using Google Map Javascrpt API
See the documenation for google.maps.geometry.poly.isLocationOnEdge:
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
proof of concept fiddle
code snippet:
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
clickable: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
google.maps.event.addListener(map,'click',function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map,
draggable: true
});
var contentStr;
if (google.maps.geometry.poly.isLocationOnEdge(marker.getPosition(), flightPath, 1e-5)) {
contentStr = "on line";
} else {
contentStr = "not on line";
}
marker.contentStr = contentStr;
google.maps.event.addListener(marker,'click',function(e) {
infowindow.setContent(this.contentStr+"<br>"+this.getPosition().toUrlValue(6)+"<br><a href='javascript:map.setCenter(new google.maps.LatLng("+this.getPosition().toUrlValue()+"));map.setZoom(19);'>Zoom In</a>");
infowindow.open(map,this);
});
google.maps.event.addListener(marker, 'dragend', function() {
if (google.maps.geometry.poly.isLocationOnEdge(this.getPosition(), flightPath, 1e-5)) {
contentStr = "on line";
} else {
contentStr = "not on line";
}
this.contentStr = contentStr;
});
google.maps.event.trigger(marker,'click');
});
}
google.maps.event.addDomListener(window, "load", initialize);
html, body, #map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>

getJSON google maps Polyline

This is an example from my jsonData:
"lineformap":"new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)"
and this is my code:
(no line appears)
When i copy the data in to the code the lines are visable on the map
Who can help me with this
var poly;
var map;
function initialize() {
var latlng = new google.maps.LatLng(52.2554, 6.1627);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bermudaTriangle;
map = new google.maps.Map(document.getElementById("ObjectMap"), myOptions);
$.getJSON('/api/dbklineforbws', function (createbws) {
$(createbws).each(function (i, itemb) {
// Define the LatLng coordinates for the polygon's path.
var flightPlanCoordinates = [
itemb.lineformap
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
For me it's very strange usage of json file. But, to make it work I'd change json file to:
{
"lineformap": "[new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)]"
}
and
var flightPlanCoordinates = [
itemb.lineformap
];
to
var flightPlanCoordinates = eval(itemb.lineformap);
to get polyline.