GoogleMap on a webpage - javascript

I use the below code for my webpage, but I want the map show the border as in this example.
How can I figure it out?
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script language="javascript" type="text/javascript">
var map;
var geocoder;
function InitializeMap() {
var latlng = new google.maps.LatLng(39.646859, 27.883121);
var myOptions =
{
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function FindLocation(whichone) {
geocoder = new google.maps.Geocoder();
InitializeMap();
var control1 = document.getElementById('<%= DDL_Ilce.ClientID %>');
var selectedvalue1 = control1.options[control1.selectedIndex].text;
var control2 = document.getElementById('<%= DDL_Mahalle.ClientID %>');
var selectedvalue2 = control2.options[control2.selectedIndex].text;
if (whichone == 1) {
var address = " Balıkesir" ;
}
else
{
var address = selectedvalue2 + " Balıkesir" ;
}
alert(address);
geocoder.geocode({ 'address': address, 'region':'Turkey' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
window.onload = InitializeMap;
</script>

Add in the Polyline method. As an example place something like this inside your InitializeMap() function:
var flightPlanCoordinates = [
{lat: 39.646859, lng: 27.883121},
{lat: 40.646859, lng: 28.883121},
{lat: 42.646859, lng: 30.883121},
{lat: 43.646859, lng: 32.883121},
{lat: 39.646859, lng: 27.883121}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
So that your function looks like this now:
function InitializeMap(){
var latlng = new google.maps.LatLng(39.646859, 27.883121);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true };
map = new google.maps.Map(document.getElementById("map"), myOptions);
var flightPlanCoordinates = [
{lat: 39.646859, lng: 27.883121},
{lat: 40.646859, lng: 28.883121},
{lat: 42.646859, lng: 30.883121},
{lat: 43.646859, lng: 32.883121},
{lat: 39.646859, lng: 27.883121}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
You can read more about it here:
https://developers.google.com/maps/documentation/javascript/shapes

Related

How to add multiple markers in Gmap3?

I am trying to add multiple marker in gmap3. but it can't work.
If anybody any idea how to add multiple location in gmap3 API.
var contactmap = {
lat: 24.091328,
lng: 38.037067
};
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker({
position: contactmap,
icon: 'assets/img/map-marker.gif'
})
This code is view only one marker. So how can I add multiple marker in Map?.
So finally I found the Right solution with myself so thanks to support me.
var locations = [
['Yanbu Saudi Arabia', 24.091328, 38.037067, 1],
['Yanbu Saudi Arabia', 24.005421, 38.197395, 2]
];
var map = new google.maps.Map(document.getElementById('tm-map'), {
zoom: 10,
center: new google.maps.LatLng(24.005421, 38.197395),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = [];
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
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
console.log(markers[0]);
create an array of markers and then push each new marker object into that array and finally pass array into your marker()
follow this github response https://github.com/jbdemonte/gmap3/issues/123
for any future problems refer to their github page.
// this is how you create array
var multiadress = [{latLng:[1,2],content:"abcd"},{latLng:[3,4],content:"pqr"},{latLng:[6,7],content:"kbc"}]
var markers = [];
$.each(multiadress, function(key, val){
var latLng = val.latLng
markers.push({
position: latLng,
content: val.content
});
});
var contactmap = {
lat: 24.091328,
lng: 38.037067
};
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker(markers)
accept answer if it helps you.
You can pass a markerList:
var markers = [
{ lat: 37.772, lng: -122.214 },
{ lat: 21.291, lng: -157.821 },
{ lat: -18.142, lng: 178.431 },
{ lat: -27.467, lng: 153.027 }
];
function markerSetup(markers){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var icon = {
url: "../Content/Images/Car.png", // url
scaledSize: new google.maps.Size(50, 60), // scaled size
origin: new google.maps.Point(0, 0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
// alert(markers[0].lat)
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
// map.setMap(trafficLayer);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
icon: icon,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
map.setZoom(12)
});
}
It's workable code. Hope it's help you.
I do it like this:
$('#tm-map')
.gmap3({
zoom: 13,
center: contactmap,
scrollwheel: false,
mapTypeId: "shadeOfGrey",
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, "shadeOfGrey"]
}
})
.marker(
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'},
{position: [51.552970, 8.560290], icon: 'assets/img/map-marker.gif'}
)

Add marker with label in google map's every end of polyline

I've multiple polylines, I want a marker on every end and start of polyline with a label, I am tracking bike movement, I am getting the polyline but i need to display the time on poly line or on the end point, if i can show the time in the polyline it would be great. I am developing a tracking system, i am getting the lat long, of start and end points i am also abple to draw polylines, i want to display time on the polyline or at least display a marker on every end and show the time... below is my code
var bikearray = [];
$('#searchbtn').on('click', function() {
$.ajax({
url:'http://metrobikes.in/api/a2b-bike-movement-on-map',
method:"GET",
data : {
start_Date : "2017-12-11",
end_date : "2018-01-24",
bike_number : "KA-51-D-6109"
},
}).done(function(data){
bikearray = data.result.data;
initMap();
});
});
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{lat: from_lat, lng: from_long},
{lat: to_lat, lng: to_long}
],
icons: [{
icon: lineSymbol,
repeat:'35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
To add a marker to the beginning and end of the polyline, add a marker to the beginning point and to the ending point. To add the time in an InfoWindow on the end marker, add that as well (and trigger a click on it to open it):
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {lat: from_lat, lng: from_long}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {lat: to_lat, lng: to_long}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
proof of concept fiddle
code snippet:
var bikearray = [{
from_lat: 12.98966,
from_long: 77.653637,
to_lat: 12.9715987,
to_long: 77.5945626,
colour: "blue",
time: "12:00"
},
{
from_lat: 13.0826802,
from_long: 80.2707184,
to_lat: 12.9922145,
to_long: 77.7159,
colour: "red",
time: "11:00"
},
]
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for (i = 0; i < bikearray.length; i++) {
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {
lat: from_lat,
lng: from_long
}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long = parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {
lat: to_lat,
lng: to_long
}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}
})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{
lat: from_lat,
lng: from_long
},
{
lat: to_lat,
lng: to_long
}
],
icons: [{
icon: lineSymbol,
repeat: '35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
Looks like this was already answered in Text Within Polyline Google Maps V3
One solution would be using this library from github:
https://github.com/googlemaps/js-map-label
You could use it like this:
var labelPosition = new google.maps.LatLng(middle_lat, middle_long);
var mapLabel = new MapLabel({
text: "Your text",
position: labelPosition ,
map: map,
fontSize: 12
});
You would have to calculate the Middle-Point between the two points.

Fill variable with values from click event

I am trying to make a routeplanner which allows users to click on random points on the map and create a route.
Now I'm having some trouble getting the values into the polyline variable.
I have searched around on Google but I can't seem to find a way to keep adding values on top of already existing values. These values come from the click event on the map.
So how do I add values to a variable with the same format on each click event?
function initMap() {
var location = {
lat: 51.3554957,
lng: 5.4533268000000135
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: location
});
google.maps.event.addListener(map, "click", function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log(latitude + ', ' + longitude);
});
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,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBpQwkFGfliyQ_B52NBJFEyQd1_fD8gV6g&callback=initMap">
</script>
</body>
</html>
Expected result (4 clicks):
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
}
];
Take a look at the following:
function initMap() {
var flightPlanCoordinates = [];
var location = {
lat: 51.3554957,
lng: 5.4533268000000135
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: location
});
google.maps.event.addListener(map, "click", function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log(latitude + ', ' + longitude);
flightPlanCoordinates.push({lat: latitude, lng: longitude});
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
}
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBpQwkFGfliyQ_B52NBJFEyQd1_fD8gV6g&callback=initMap">
</script>
</body>
</html>

Filling Google Maps polygon from array of LatLng points

I have an array of coordinates in LatLng format. I would like to construct a polygon using those coordinates. I know I can hardcode a polygon with individual coordinates like this:
var triangleCoords = [
{lat: A, lng: A},
{lat: B, lng: B},
{lat: C, lng: C}]
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?
Correct me if I had misunderstood your question.
Q:
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?
A:
Short answer: No. Unfortunately there is no smartness in the google.maps.Polygon code which would magically try to figure out the lat and lng coordinates of the specified google.maps.LatLng objects for you.
You will need to use the lat() and lng() APIs to return the raw coordinate values from the google.maps.LatLng object and plug that into your array. No shortcut.
Example:
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 coordinateA = new google.maps.LatLng(18.979026,72.949219);
var coordinateB = new google.maps.LatLng(28.613459,77.255859);
var coordinateC = new google.maps.LatLng(22.512557,88.417969);
var coordinateD = new google.maps.LatLng(12.940322,77.607422);
var coords =
[
{lat: coordinateA.lat(), lng: coordinateA.lng() },
{lat: coordinateB.lat(), lng: coordinateB.lng() },
{lat: coordinateC.lat(), lng: coordinateC.lng() },
{lat: coordinateD.lat(), lng: coordinateD.lng() }
];
metros = new google.maps.Polygon(
{
paths: coords,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
See here for a working JSFiddle example.
http://jsfiddle.net/SamuelToh/3srggbmu/
Here same way am trying polygon google route map dynamically from mysql, it work only on marker, but its not working in polygon ,
here is the code
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 5,
center: { lat: 13.36, lng: 77.03 },
});
var planCoordinates = new Array();
// var locations = [
// {lat: 13.367797388285002, lng:77.03707749682616},
// {lat:13.341074247677549, lng:77.0394807561035},
// {lat:13.379153826558369, lng: 77.08685929614256},
// {lat: 13.367797388285002, lng:77.03707749682616},
// ];
<?php
if ($result->num_rows > 0)
{
foreach($result as $key => $row)
{
?>
var locations = [{lat: <?php echo $row['lat']; ?>,lng: <?php echo $row['lng']; ?>}];
for (let i = 0; i < locations.length; i++) {
let obj = locations[i];
planCoordinates[i] = new google.maps.LatLng(obj.lat, obj.lng);
var myLatlng = new google.maps.LatLng(obj.lat, obj.lng);
poly = new google.maps.Polygon({
path: planCoordinates,
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
poly.setMap(map);
var infoWindow = new google.maps.InfoWindow({ content: contentString.this });
var marker = new google.maps.Marker({
position: myLatlng,
title: "Jumbookart",
zIndex: 999,
});
marker.setMap(map);
let ikonica = new google.maps.Marker({
position: myLatlng,
title: "Markeri",
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 7
}
});
ikonica.setMap(map);
}
<?php } } ?>
var arrayOfFlightPlans = [locations];
//Loops through all polyline paths and draws each on the map.
for (let i = 0; i < arrayOfFlightPlans.length; i++) {
flightPath = new google.maps.Polygon({
path: arrayOfFlightPlans[i],
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
flightPath.setMap(map);
}
}

How to make google Map Api polyline with pin?

I've been created polyline maps like this
but I want set pin in every point...
like this one :
How i can do that?
this is my javascript's code...
<script>
latawal = <?php echo json_encode($locationawal['lat'])?>;
longawal = <?php echo json_encode($locationawal['lon'])?>;
var GoogleMaps = function () {
var mapPolylines = function() {
var map = new GMaps({
div: '#gmap_polylines',
lat: latawal,
lng: longawal,
click: function(e){
console.log(e);
}
});
path = [
<?php foreach ($locationawal10 as $row){ ?>
[<?php echo json_encode($row['lat'])?>, <?php echo json_encode($row['lon'])?>],
<?php } ?>
];
map.drawPolyline({
path: path,
strokeColor: 'Red',
strokeOpacity: 0.6,
strokeWeight: 4
});
}
return {
//main function to initiate map samples
init: function () {
mapPolylines();
}
};
}();
</script>
Thanks before.... I hope someone can help me about this... sorry for my bad english..
It seems you need to make multiple markers. You will be using the latlang values from your latawal and longawal json files for each marker as LatLng values for the markers. Check this SO thread for additional reference.
I did a quick demo for you to convey the idea. You may need to modify parts which needs cleaner coding. This is the relevant part:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var flightPlanCoordinates = [
{lat: -32.342841, lng: 119.882813},
{lat: -32.194209, lng: 144.492188},
{lat: -19.248922, lng: 145.546875},
{lat: -18.916680, lng: 124.804688}
];
var markerCoordinates = [
[-32.342841, 119.882813],
[-32.194209, 144.492188],
[-19.248922, 145.546875],
[-18.916680, 124.804688]
];
var marker, i;
for (i = 0; i < markerCoordinates.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markerCoordinates[i][i-i], markerCoordinates[i][1]),
map: map,
title: 'Hello World!'
});
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
This is what it looks like:
It would defintely help if you read the docs about Markers too.
Simplest solution is to process the path and add markers at each vertex.
for (var i=0; i<path.length; i++) {
map.addMarker({
lat: path[i].lat,
lng: path[i].lng,
})
}
proof of concept fiddle
code snippet:
function initialize() {
latawal = 41.5;
longawal = -72.4;
var GoogleMaps = function() {
var mapPolylines = function() {
var map = new GMaps({
div: '#gmap_polylines',
lat: latawal,
lng: longawal,
zoom: 8,
click: function(e) {
console.log(e);
}
});
path = [{
lat: 42,
lng: -72
}, {
lat: 41,
lng: -72.4
}, {
lat: 41.5,
lng: -72.6
}];
map.drawPolyline({
path: path,
strokeColor: 'Red',
strokeOpacity: 0.6,
strokeWeight: 4
});
for (var i = 0; i < path.length; i++) {
map.addMarker({
lat: path[i].lat,
lng: path[i].lng,
})
}
}
return {
//main function to initiate map samples
init: function() {
mapPolylines();
}
};
}();
GoogleMaps.init();
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#gmap_polylines {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.12/gmaps.min.js"></script>
<div id="gmap_polylines"></div>

Categories