When Google Map load, it cost several seconds to load all submaps, each time i want to change a marker i need to load all map again and again, it is possible to load map once and update markers dynamic?
function initialize(markers) {
console.log(markers);
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(40.4378271,-3.6795367)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var j=0;
for (var i=0;i<((markers.length)-3);i=i+3){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i],markers[i+1]),
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+j+'|FE6256|000000',
title: markers[i+2]
});
j++;
}
}
google.maps.event.addDomListener(window, 'load', initialize(markers()));
You must store the Map-instance somewhere where it's accessible inside initialize, then you'll be able to re-use the Map on further calls and must only remove previous markers and draw the new markers.
Sample(stores the Map as property of the map-div):
function initialize(markers) {
var node = document.getElementById('map-canvas'),
j = 0,
marker;
//create a single Map-instance and store it as property of the map-container
if (!node.map) {
//create a MVCObject, used for binding of the markers map-property
node.mvc = new google.maps.MVCObject();
//the map
node.map = new google.maps.Map(node, {
zoom: 2,
center: new google.maps.LatLng(40.4378271, -3.6795367)
});
}
//this will remove previous markers
node.mvc.set('map', null);
node.mvc.set('map', node.map);
for (var i = 0; i < ((markers.length) - 3); i = i + 3) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i], markers[i + 1]),
map: node.map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' +
j + '|FE6256|000000',
title: markers[i + 2]
});
//bind the markers map-property
marker.bindTo('map', node.mvc, 'map', true);
google.maps.event.addListener(marker, 'map_changed', function () {
//remove the binding when map has been set to null
if (!this.getMap()) {
this.unbind('map');
}
});
j++;
}
}
Demo: http://jsfiddle.net/doktormolle/ns7j3sx0/
Related
I am working with Google maps API(latest). So far, i can able to create and removing(on add operation) route with the help of polylines and markers.
Problem is when i try to modify(on update mode) the maps populates(dynamically) the route which i saved but if try to remove/modify existing route the marker removes but polyline dont.
tried poly.setMap(null);. but doesn't work.
on page load :
after removing any marker : (the last one got removed)
And you can see marker has been removed but polyline is still there
CODE(not working on fiddle):
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// if update/edit model populate map dynamically
populateLatLng();
// Add a listener for the click event
map.addListener('click', addLatLng);
map.addListener('click', function() {
getPathVariableCode(poly);
});
}
function populateLatLng() {
var path = '[{"lat":24.96078338154793,"lng":67.10892827306634},{"lat":24.934323836524374,"lng":67.07047612462884},{"lat":24.926851877301345,"lng":67.08111912999993},{"lat":24.90816999805268,"lng":67.06669957433587},{"lat":24.917822655664953,"lng":67.0519366959179},{"lat":24.911102310371437,"lng":67.03740863310293}]' //dynamic array
path = JSON.parse(path);
for (k = 0; k < path.length; k++) {
var marker = new google.maps.Marker({
position: path[k],
title: '#' + k,
map: map
});
markers.push(marker);
poly = new google.maps.Polyline({
path: path,
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function getPathVariableCode(line) {
var getLocation = '';
var locationArr = [];
var pathArr = line.getPath();
for (var i = 0; i < pathArr.length; i++) {
var codeStr = [];
codeStr = {
'lat': pathArr.getAt(i).lat(),
'lng': pathArr.getAt(i).lng()
};
locationArr.push(codeStr);
document.getElementById('locationCordinates').value = JSON.stringify(locationArr);
}
};
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
getPathVariableCode(poly);
}
}
}
#map {
height: 200px;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
Your code is quite problematic but I was able to successfully get a simplified working version of what you're trying to achieve here (if I understood correctly).
Try the code below. Just click on the map to add markers and then click on those markers to remove both the markers and their corresponding lines.
var poly;
var map;
var markers = new Array();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 24.926294,
lng: 67.022095
} // Center the map on Pakistan.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event, path = false) {
console.log("event", event);
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map,
id: new Date()
});
markers.push(marker);
console.log(markers.length - 1, event.latLng);
poly.getPath().setAt(markers.length - 1, event.latLng);
google.maps.event.addListener(marker, 'click', function(event) {
removePoint(marker);
});
}
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id === marker.id) {
markers[i].setMap(null);
markers.splice(i, 1);
poly.getPath().removeAt(i);
}
}
}
I hope this helps point you in the right direction.
I receive json data from a server and need to add them to a google map. It works fine, however, I only see one marker and I assume every time I add a marker it changes it to new coordinates and doesnt add an extra marker. How can I define markers as an array?
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: this["gsx$instruments"][prop]
});
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Add a new function addMarker and use that function to include markers also keep the map variable outside the ajax call as well. updated code below
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: {lat: LAT, lng: LONG}
});
function addMarker(position, map, title){
var marker = new google.maps.Marker({
position: position,
map: map,
title: title
});
}
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
addMarker(myLatLng,map,this["gsx$instruments"][prop]);
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Essentially, you first need to add the markers to an array of markers
Suppose you have JSON providing the markers and supposing each marker has a name and coordinates attributes
function formatMarkers (){
// Loop through all of the JSON entries provided in the response
for (var i = 0; i < markersArray.length; i++) {
var markers = markersArray[i];
// Create popup windows for each record
var contentString = '<p><b>Name</b>: ' + markers.name + '</p>';
// Converts each of the JSON records into Google Maps Location format
formattedMarkers.push({
latlon: new google.maps.LatLng( markers.coordinates[1], markers.coordinates[0] ),
message: new google.maps.InfoWindow({
content: contentString,
maxWidth: 320
}),
username: markers.name
});
}
return formattedMarkers;
}
Then you need to render each of them
formattedMarkers.forEach(function (n) {
var marker = new google.maps.Marker({
position: n.latlon,
map: map,
icon: icon
});
// For each marker created, add a listener that checks for clicks
google.maps.event.addListener(marker, 'click', function () {
// When clicked, open the selected marker's message
n.message.open(map, marker);
});
marker.setMap(map);
}
I hope I've been helpful.
I have a Google map. I created some markers, but I can not hide these markers. I looked at this document. I have one function, but it failed.
function LoadMap () {
var markers = JSON.parse('<%=Stations() %>');
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
map2 = new google.maps.Map(document.getElementById("map_canvas2"), mapOptions2);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map2,
title:"Hello",
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
icon: InitIcon
});
}(marker, data);
}
}
You need to apply the setMap(null) to your Array of markers.
If your markers variable contains all your markers, you need to loop through each markers and delete each of them using
markers[i].setMap(null);
as shown on your sample
BTW, your code contains somme errors, like a missing ; after var data = markers[i]
In my project I want to move the center of the map to new coordinates. This is the code I have for the map
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function moveToLocation(lat, lng){
var center = new google.maps.LatLng(lat, lng);
var map = document.getElementById("map_canvas");
map.panTo(center);
}
The moveToLocation function does get called but the map does not re center. Any idea what I'm missing?
Your problem is that in moveToLocation, you're using document.getElementById to try to get the Map object, but that only gets you an HTMLDivElement, not the google.maps.Map element you're expecting. So your variable map has no panTo function, which is why it doesn't work. What you need to is squirrel the map variable away somewhere, and it should work as planned. You can just use a global variable like so:
window.map = undefined; // global variable
function initialize() {
const mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// assigning to global variable:
window.map = new google.maps.Map(
document.getElementById("map_canvas"), mapOptions);
}
function moveToLocation(lat, lng){
const center = new google.maps.LatLng(lat, lng);
// using global variable:
window.map.panTo(center);
}
See working jsFiddle here: http://jsfiddle.net/fqt7L/1/
Display the Google Maps API using dynamically, fetch the data in database to display the place, lat, long and to show map marker in center using AngularJS. Done by Sureshchan...
$(function() {
$http.get('school/transport/scroute/viewRoute?scRouteId=' + scRouteId).success(function(data) {
console.log(data);
for (var i = 0; i < data.viewRoute.length; i++) {
$scope.view = [];
$scope.view.push(data.viewRoute[i].stoppingName, data.viewRoute[i].latitude, data.viewRoute[i].longitude);
$scope.locData.push($scope.view);
}
var locations = $scope.locData;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId : google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var marker, j;
for (j = 0; j < locations.length; j++) {
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[j][1], locations[j][2]),
map : map
});
google.maps.event.addListener(marker, 'click', (function(marker, j) {
bounds.extend(marker.position);
return function() {
infowindow.setContent(locations[j][0]);
infowindow.open(map, marker);
map.setZoom(map.getZoom() + 1);
map.setCenter(marker.getPosition());
}
})(marker, j));
};
map.fitBounds(bounds);
});
});
I have three arrays : myLats, (latitudes) myLngs (longitudes) and myLocs (address strings)
e.g. myLats[0] = 53.3534751, ,myLngs[0] = -2.5682085, myLocs[0] = Longwood Rd Appleton Warrington. So the elements of each array all correspond to each other numerically.
When constructing the map in my initialize() function, I loop through these to place multiple markers at the correct coordinates, and i'm also trying to have each marker having an infowindow appear when clicked, yet when i click a marker an infowindow simply does not appear. Any help with this would be greatly appreciated.
Code:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(54.00366, -2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker, infowindow, i;
for (i = 0; i <= myLats.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i], myLngs[i]),
map: map,
clickable: true,
icon: '". url::base() ."resources/icons/accident.png',
});
infowindow = new google.maps.InfoWindow({
content: myLocs[i],
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
}
That's a common problem when dealing with more than one marker. You aren't in fact creating a new window for each marker but must redefining the single window for each marker.
You'll find the problem and solution on page 88 onwards of Google Map API V3
If you are new to Google Maps API, I would recommend reading that book, it gave me a great start and I avoided a lot of the "common" mistakes.
Hope this helps.
Jim
I made a few changes, like adding the markers inside a function, adding 'var', and changing i <= myLats.length to i < myLats.length. It was a combination of these changes that made it work.
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
var marker, infowindow, i;
for (i=0; i < myLats.length; i++)
{
addMarker(i);
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true,
//icon: '". url::base() ."resources/icons/accident.png',
});
var infowindow = new google.maps.InfoWindow({
content: myLocs[i]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
However, I'm guessing you want a solution that keeps only one infowindow open, I had this figured out first:
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
var map, marker, infowindow, i;
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
infowindow = new google.maps.InfoWindow({ });
for (i = 0; i < myLats.length; i++) {
addMarker(i);
}
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true
//icon: '". url::base() ."resources/icons/accident.png'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(myLocs[i]);
infowindow.open(map,marker);
});
}