Draw multiple polygon on google maps API v3 javascript - javascript

I have several coordinate data saved on my database. The data looked like this:
[
[-8.411328650721382, 115.2549934387207],
[-8.423385320191324, 115.26924133300781],
[-8.428988996455418, 115.27507781982422],
[-8.445120338164106, 115.2682113647461],
[-8.452082077411186, 115.2656364440918],
[-8.46430726648532, 115.26580810546875],
[-8.470419715493609, 115.26615142822266],
[-8.476022708444539, 115.26477813720703],
[-8.481116267546547, 115.25671005249023],
[-8.492491639030948, 115.24469375610352],
[-8.481795403659492, 115.2414321899414],
[-8.472287388879758, 115.24641036987305],
[-8.462609346758175, 115.24606704711914],
[-8.455308206642881, 115.24417877197266],
[-8.445629737978635, 115.23714065551758],
[-8.434252981999162, 115.2352523803711],
[-8.422026840993878, 115.23490905761719],
[-8.410479575344654, 115.23954391479492],
[-8.405385084022475, 115.24383544921875]
]
I have to draw several polygon on map but when I do, all the polygons are connected each other.
Here is my javascript:
<script>
var map;
var i = 0;
var poly = {};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -1.55038056899795, lng: 118.6962890625},
zoom: 5,
disableDefaultUI: true
});
var jsonPeta = <?=$peta?>;
var coordArray = [];
var path = [];
for(i=0;i<jsonPeta.length;i++){
//console.log(i);
coordArray = JSON.parse(jsonPeta[i].peta);
coordArray.forEach(function(entry){
path.push(new google.maps.LatLng(entry[0],entry[1]));
});
poly[i] = new google.maps.Polygon({
paths: path,
editable: false,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#03a9f4',
clickable: true,
fillOpacity: 0.35
});
poly[i].setMap(map);
console.log(poly[i]);
}
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
//document.getElementById("lat").value = place.geometry.Latitude
}));
document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lon').value = place.geometry.location.lng();
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>

Related

Markers on multiple coordinates on Google Map in JavaScript

I have two sets of points coordinates that I need to connect on google map, like this, just much larger:
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
The first coordinate from "start" needs to be connected to the first coord from "end", and so on, until the end. Got that, but now I need to make "start" and "end" points more recognizable, put some kind of dots in a different color on them. What I have:
var geocoder;
var map;
function initialize() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
var paths = [];
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
}
map.fitBounds(bounds);
var polyline = new google.maps.Polygon({
paths: paths,
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
google.maps.event.addDomListener(window, "load", initialize);
Any kind of help is welcomed.
The simplest thing you can just create markers for start and end points. Like the following code
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
//Create start and end markers
var markerStart = new google.maps.Marker({
position: startPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
draggable: true,
map: map
});
var markerEnd = new google.maps.Marker({
position: endPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'green',
strokeColor: 'green'
},
draggable: true,
map: map
});
}
It will give you something like
Code snippet
var map;
function initMap() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var start = ['42.81405, 12.4886861111', '32.7994444444, 20.506775', '44.8062644989, 20.5005495758'];
var end = ['47.81405, 18.4886861111', '33.7994444444, 21.506775', '39.8062644989, 16.5005495758'];
var paths = [];
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
//Create start and end markers
var markerStart = new google.maps.Marker({
position: startPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'blue',
strokeColor: 'blue'
},
draggable: true,
map: map
});
var markerEnd = new google.maps.Marker({
position: endPt,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: 'green',
strokeColor: 'green'
},
draggable: true,
map: map
});
}
map.fitBounds(bounds);
var polyline = new google.maps.Polygon({
paths: paths,
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"
async defer></script>

The Google Maps JavaScript API is not zooming when I change the default zoom setting

The zoom is set to 8 and I am using a KmlLayer for a radius. No matter what I change the zoom setting to the zoom level stays the same on the website: http://mainelyknowleslobster.com/delivery/.
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: 28.53687, lng: -81.38328},
center: {lat: 28.5893244, lng: -81.3744571},
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//Add marker and popup info
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4 id="firstHeading" class="firstHeading">MAINEly Knowles Lobster</h4>'+
'<div id="bodyContent">'+
'<p><center>887 Jackson Ave<br> Winter Park, FL 32789<br> Phone: 407-960-7441<br> Contact Us!</center></p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: {lat: 28.5893244, lng: -81.3744571},
map: map,
title: 'MAINEly Knowles Lobster'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// Polygon
var ctaLayer = new google.maps.KmlLayer({
url: 'http://mainelyknowleslobster.com/map/circle.kml',
map: map
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
</script>
I read somewhere that it might have something to do with the perspective of the viewport. I added the preserveViewport property but this did not solve the problem. I wonder if the KML layer has anything to do with it:
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true
});
You need to set preserveViewport: true for the KmlLayer
// Polygon
var ctaLayer = new google.maps.KmlLayer({
url: 'http://mainelyknowleslobster.com/map/circle.kml',
preserveViewport: true,
map: map
});
proof of concept fiddle

Getting Coordinates from Another HTML Element for GMAP

So far I have been trying to implement a simulation for aircraft trip on GMaps.But I encountered an error or a logic (whatever you call) that I couldn't figure out.
In my project briefly I made an database connection to get Runway coordinates then I recieved succesfully and got them to write in labels after then I tried to reach labels through javascript to get coordinates again to enter GMaps but It didn't work.(Map is not opening)
I would be very pleasent,If you could help me.
Thanks in Advance
<script>
var latstrt = 0;
var longtstrt = 0;
function Load()
{
latstrt = document.getElementById("<%=Label6.ClientID %>").innerHTML;
longstrt = document.getElementById("<%=Label7.ClientID %>").innerHTML;
window.alert(latstrt);
}
window.onload = function () {
Load();
initialize();
};
window.alert(latstrt);
var myCenter = new google.maps.LatLng(latstrt,longtstrt);
var elaziz = new google.maps.LatLng(38.608334, 39.291668);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
draggable: true,
});
var myTrip = [myCenter,elaziz];
var flightPath = new google.maps.Polyline({
path: myTrip,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
marker.setMap(map);
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's a slightly modified version of your code which should work:
function initialize() {
var latstrt = document.getElementById("<%=Label6.ClientID %>").innerHTML;
var longstrt = document.getElementById("<%=Label7.ClientID %>").innerHTML;
var myCenter = new google.maps.LatLng(latstrt,longtstrt);
var elaziz = new google.maps.LatLng(38.608334, 39.291668);
var mapProp = {
center: myCenter,
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
draggable: true,
map: map
});
var myTrip = [myCenter,elaziz];
var flightPath = new google.maps.Polyline({
path: myTrip,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Google Maps Engine API - KML Layers Obstructing New Markers Event

I am currently building out a small widget that allows someone to see a kml heat map of the united states population density then select an area on that map and drop a market on to that location. The user then enters a number and that creates a mile radius to show the user how much area they cover.
My problem is that I have 63 .kml files for just one state in the US. I know I can remove the xml <name> and <description> to prevent the name from popping up when clicked, but I can't see that being practical with that many .kml files.
Is there a programmatic solution or API solution to prevent just the kml layers from being clickable?
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
value: 2714856
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
value: 8405837
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
value: 3857799
};
citymap['vancouver'] = {
center: new google.maps.LatLng(49.25, -123.1),
value: 603502
};
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(34.7361, -92.3311),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].value) * 100
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
}
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml'
});
ctaLayer.setMap(map);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map-canvas"></div>
Discretionary note: Google API does not work well with Stack Overflow's code snippet's widget.
set the KmlLayer clickable option to false
clickable boolean If true, the layer receives mouse events. Default value is true.
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
value: 2714856
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
value: 8405837
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
value: 3857799
};
citymap['vancouver'] = {
center: new google.maps.LatLng(49.25, -123.1),
value: 603502
};
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(34.7361, -92.3311),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].value) * 100
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
}
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml',
clickable: false
});
ctaLayer.setMap(map);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Google Map Not Displaying Entirely

I have two maps using the Google Maps API and, to set the scene, they are both contained in a FuelUX Wizard, on separate panes.
The map on the first pane works perfectly, however on the second map on the other pane, it displays like this:
This is obviously wrong. However, If I resize the window it pops in to the proper display.
Here is the main Javascript that initializes the maps.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 5, center: new google.maps.LatLng(30.2500, -97.7500),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var map2 = new google.maps.Map(document.getElementById('map-canvas-2'), {
zoom: 5, center: new google.maps.LatLng(30.2500, -97.7500),
mapTypeId: google.maps.MapTypeId.HYBRID
});
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var input2 = /** #type {HTMLInputElement} */(
document.getElementById('pac-input-2'));
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
var searchBox2 = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input2));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
//Map 2
google.maps.event.addListener(searchBox2, 'places_changed', function() {
var places = searchBox2.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map2: map2,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map2.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
google.maps.event.addListener(map2, 'bounds_changed', function() {
var bounds = map2.getBounds();
searchBox2.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You need to trigger a map resize when the tab is shown. You have an available event in FuelUX: changed.fu.wizard that fires when the step changes and displays to the user.
$('#myWizard').on('changed.fu.wizard', function () {
// Trigger a map resize
google.maps.event.trigger(map, 'resize');
});
JSFiddle demo
Edit:
To trigger it on tab change, use the shown.bs.tab:
$('a[data-toggle="tab"]').on('shown.bs.tab', function () {
// Trigger a map resize
google.maps.event.trigger(map, 'resize');
});
JSFiddle demo

Categories

Resources