Use initialized Google Maps in other .js - javascript

I've two diffrent .js-files: scripts.js and search.js
In script.js the Google Maps is initialized:
function initMap() {
var mapDiv = document.getElementById('market-map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 12345, lng: 12345},
zoom: 8
});
}
It's working fine.
But I need this map in search.js as a variable, so I can work with this map in search.js (add Geocoder etc.)
Does anyone know a solution, how I can fix this problem?
Thanks for your help. :)

You just have to set map as a globale variable
var map = null;
function initMap() {
var mapDiv = document.getElementById('market-map');
map = new google.maps.Map(mapDiv, {
center: {lat: 12345, lng: 12345},
zoom: 8
});
}
Then, search.js will access to it.

Related

Delete heat map for refreshing

I have a heat map in my webpage. It works fine but I have to refresh the whole page to get new values.
I am changing it now to get values each 5 seconds and paint new values.
Also works fine. But I think new values are being painted over old ones because I get each 5 seconds a brighter noise point.
How do I remove painted values and paint new ones?
function initialize() {
mapOptions = {
zoom: 16,
center: new google.maps.LatLng(lat, lon),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
initValues();
}
function initValues(){
pointArray = new google.maps.MVCArray(taxiData);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setOptions({radius: 40});
heatmap.setMap(map);
}
In taxiData I have the updated values each time I call initValues function. I call once initialize and then, every 5 seconds, I update taxiData and call initValues.
For anyone else searching for this I found the following worked.
Begin by declaring the variable as a global that will hold the heatmap MVCObject.
var mvcObj;
Then, in the function you use to add the heatmap
if( typeof( mvcObj )=='object' ) mvcObj.clear();
/* locations is an array of latlngs */
mvcObj = new google.maps.MVCArray( locations );
/* this.map is a reference to the map object */
var heatmap = new google.maps.visualization.HeatmapLayer({
data: mvcObj,
map: this.map
});
This should work (hide the old heatmap before adding the new one):
function initialize() {
mapOptions = {
zoom: 16,
center: new google.maps.LatLng(lat, lon),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
initValues();
}
function initValues(){
pointArray = new google.maps.MVCArray(taxiData);
if (!!heatmap && !!heatmap.setMap)
heatmap.setMap(null);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setOptions({radius: 40});
heatmap.setMap(map);
}

javascript/google maps: convert location object to string

I am trying to find out how to convert the following object from using the google location api into a string
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
The above pulls your location. However, I can't figure out a way to see what it is as a string so that I can work with it. When I alert it, I get undefined and I've tried usual suspect properties and they don't display. I need to find out what it is so I can feed it into the directions service which takes "Boston" or lat lon or similar string an input.
Please refer the below link.
http://jsfiddle.net/y829C/1/
Here you can enter zip code and get the latitude and longitude.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': addresscity }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
var myLatlng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Working with google.maps.Geocoder(). Asynchronous callback

I've been trying to geocode an address into LatLng coordinates, but I'm having a lot of difficulty doing so. I know geocode() is an asynchronous function, and I have been toying with callbacks with no avail. I've been looking at other posts like this one (How to return value from an asynchronous callback function?), but I'm having difficulty understanding the concept. If anyone can show me how to properly do that callback function, will be much appreciated. Lot of headache over this one. Was able to get the callback to do an alert() that gives the correct LatLng, but not set the position parameter. Sorry couldn't figure it out from the example cited earlier. Pretty new to the language. Any references you can point me to to understand the concept are greatly appreciated as well. Thanks!
var location;
var image;
var map;
var geocoder;
var address;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.763146, -73.3776),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
addressSet(function(address) {
console.log(address);
// tried to set location = address;, location = new google.maps.LatLng(address);
// neither works
});
addMtsToMap(location,
map,
new google.maps.MarkerImage("img/mts/skier.png", null, null, null, new google.maps.Size(50,50)));
}
function addMtsToMap(location, map, image) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow({content: "<h1>Powder!!!</h1>"});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, marker);
});
}
function addressSet(callback) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({address: "Killington+VT"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[0].geometry.location;
callback(address);
}
});
}
Sorry all. Couldn't believe what I found after messing with this for so long. I declared var map again in initialize, which made my addressSet() function pull the incorrect global map variable. Deleting the var made it work.

Resetting Center of Map in Google Maps through Javascript

I have an MVC application that is using Google Maps throughout the app. To make things simple, I've created a JavaScript file that initializes the map and sets the map display.
In my application, I want to allow a front end developer to change the center of the map location with a simple JavaScript call. Unfortunately, after declaring the map and loading the application, if you try to make a JavaScript call back to the map variable, the map JS variable (and all variables) are null. This drops the instance to the map, and does not let me change the location (I believe).
In the JS Code below, I'm trying to call setLocation from the HTML page to reset the location. This is the fail part of the code. Help is appreciated.
var map;
var geocoder;
var marker;
$(document).ready(function () {
initialize();
$(function () {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function (request, response) {
geocoder.geocode({ 'address': request.term }, function (results, status) {
response($.map(results, function (item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
select: function (event, ui) {
$("#Place_Latitude").val(ui.item.latitude);
$("#Place_Longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
});
function setLocation(lat, lon) {
var location = new google.maps.LatLng(lat, lon);
marker.setPosition(location);
map.setCenter(location);
}
function initialize() {
var location = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
center: location, zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true
});
marker.setPosition(location);
geocoder = new google.maps.Geocoder();
}
This looks bad:
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
The geocoder is asynchronous and can't return anything from the callback routine. you need to use the variables inside the callback.
There is an example of what you are trying to do here...
Have a look at theie placeMarker function and how they have initialized the map...
My suggestion would be to start with this example and make sure that works. If so, it should be relatively straight forward to determine what is different in your implementation.

Google Maps API v3 custom markers not appearing

I want to display on my website something similar to google maps transit directions, so I am trying to display multiple different types of directions on the same map. For exmaple, I want to show a trip where you walk to the bus, take the bus to some other street, and then walk to your final destination.
To do this, I am trying to get the result of multiple directions requests on the same map with custom markers. I have a function called change_map(), which is supposed to display the information for one of these trips on the map.
I have 2 problems:
the markers do not show up on the map.
when fitbounds is un-commented, I get a stack limit exceeded error
I am new to javascript, sorry if my code sucks and thanks for your help!
var trip_map
function renderDirections(result) {
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(trip_map);
directionsDisplay.suppressMarkers = true;
directionsDisplay.setDirections(result);
}
function requestDirections(start, end) {
var directionsService = new google.maps.DirectionsService;
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
}
function change_map(pk) {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
trip_map = new google.maps.Map(document.getElementById("trip_map"),
myOptions);
var bounds = new google.maps.LatLngBounds();
for (var j = 0; j < latlngpairs.length; j++) {
var GPS = new google.maps.LatLng({lat:latlngpairs[0],
lng:latlngpairs[1]});
var end_marker = new google.maps.Marker({position: GPS,
map: trip_map,
title: "Hello World!"});
bounds.extend(end_GPS);
}
requestDirections(parts[j], parts[j+1]);
}
//trip_map.fitBounds(bounds);
}
I believe the problem is that you are passing a single object as argument to the constructor of LatLng inside the loop
Change
var GPS = new google.maps.LatLng({lat:latlngpairs[0],lng:latlngpairs[1]});
with
var GPS = new google.maps.LatLng(latlngpairs[0],latlngpairs[1]);
Hope that solves it.

Categories