+ 2
How to redirect to a marker by clicking on a button outside the initMap function?
Hello, I would like to click on the button to switch to the nearest marker on the map, which I previously obtained by sorting markers. The functions I made to get an array of markers sorted by distance from nearest to farthest are outside the initMap function. My question is how can I jump to that nearest sorted marker by clicking button. The function name in my map.js file that is called by clicking is find_closest_marker, I am sending my code below. https://code.sololearn.com/Wht9bZpBq9Mj/?ref=app
5 ответов
+ 2
You can change the startPosition to the position of the closest marker and the invoke initMap().
https://code.sololearn.com/WAvaZz63mnh0
+ 2
Thank you man a lot, I struggled with this task for a while. Can you briefly explain to me how you came up with the solution and why this
startPosition.lat = closestMarker.position.lat()
startPosition.lng = closestMarker.position.lng() ?
does it mean that initMap() should always be called at the end of a function that is not in scope of initMap function?
+ 2
Filip
The solution I provided in my previous reply is based on the fact that initMap is a function and that startingPosition is initialized and assigned values outside of initMap.
No, you don't have to use initMap() at all. While this is a working solution, it is also a naive/ brute-force type solution.
The solution suggested by google maps JS API docs is to use Map.setCenter(), but before that can be done, you must remove var from line 12. Doing this will assign the newly instantiated Map to the global MAP variable that is initialized at line 1. Now you have access to the MAP object throughout your code.
https://code.sololearn.com/W2WV1g1lMSPX
I apologize for any confusion I may have caused.
+ 2
Thanks again for the reply, I figured out roughly what you meant. Can I increase zoom on this nearest marker? e.g. When user clicks on button the app takes him away to the closest location and zoom increases.
Now value is 15 because it was set at 15 on start position.
I would like this value to remain at the starting position and increase zoom when the user click on button.
+ 1
Filip
The map zoom value is still set to 15 when it re-centers to the nearest marker.
You might need to set the zoom to something less.
https://code.sololearn.com/W2WV1g1lMSPX